If Else - Else not working.

So obviously I'm a beginner at programming and we're writing a program for one of my classes. I feel like I understand everything pretty well, but I'm stuck on a program using if/else statements. I've tried the else statement as is, and with else ( &radius <= 0 ) and neither one is working properly. Basically, what it's supposed to do is display an error message if the radius is less than or equal to 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  #include <stdio.h>

int main()
{
    float radius;
    float area;
    
    printf( "Please enter radius: " );
    scanf( "%f", &radius );
    if ( &radius > 0 ){
        area = radius * radius * 3.14;
        printf( "The area is %f", area );
        getchar();
        return 0;
    }
    else{
        printf( "error\n");
        getchar();
        return 1;
    }
}
Last edited on
This statement

if ( &radius > 0 ){

means that you are comparing the address of variable radius with zero. To compare the radius itself with 0 you should write

if ( radius > 0 ){
Thank you very much! That worked, but now it's getting stuck at the printf part? Not sure why.
What do you mean "getting stuck"?

You might want to include a \n in line 12 to flush the print buffer.
It stops at printf ("error\n"); like it's trying to calculate the area still, instead of displaying "error" and terminating.
Do you mean it stops before printing "error" or after it?
Is it waiting for the user to press a key?
It stops before printing "error" and highlights line, but doesn't tell me what's wrong with the command or what I need to change.
Matzusmc, I don't yet understand the terms used in your code, but the following simple code does what you want:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int main()
{
    float radius;
    float area;

    cout <<"Please enter radius: ";
    cin>>radius;
    if ( radius > 0 )
       {
       area = radius * radius * 3.14;
       cout<<"\nThe area is: "<< area;
       }
     else
       {
       cout<<"\nError";
       }

cin.get();
cin.get();//This seconnd one is to stop screen flash.
return 0;
}


Forgive me if you have been told to use the terms I am not yet familiar with!
It stops at printf ("error\n"); like it's trying to calculate the area still, instead of displaying "error" and terminating.


But... Your program shouldn't even attempt print "error" if the radius entered is greater than 0?

@Donnie
The program is in C, not C++. Hence, the stdio header.
Daleth, thank you. Donnie
you're saying it doesn't output the area?
try to simplify stuff by doing this: area=(radius*radius)*3.14;

Aceix.
Topic archived. No new replies allowed.