Question

I'm a very experienced Java programmer with a background in C++, but I'm just getting started with C in one of my programming classes and it's driving me nuts. This is the first assignment. It's supposed to calculate the volume or surface area of a sphere. The problem is that "radius" is equal to zero, even though the user enters the value. "mode" works just fine, which seems odd. Here is the code:

#include <stdio.h>
#define PI 3.14

int main()
{
    float radius; 
    int mode;

    printf("\nPlease enter a non-negative radius of a sphere: ");
    scanf("%f", &radius);

    printf("Please enter 1 for volume, 2 for area: ");
    scanf("%d", &mode);

    if (radius = 0)
    {
        printf("\n\nPlease enter a positive radius, instead of %f.", radius);
    }
    else
    {
        float area = 4 * PI * radius * radius;
        float volume = (4.0f / 2.0f) * PI * radius * radius * radius;
        float result = 0;

        if(mode == 1)
        {
            printf("\n\nYou are computing volume."); 
            result = volume;
        }
        else
        {
            printf("\n\nYou are computing area.");                              
            result = area;
        }

        printf("\n\nThe result is %2f", result); 
    }

    fflush(stdin);
    getchar();

    return 0; 
}

Any idea why radius isn't being stored correctly? FYI - most of this code was pre-written. I'm just supposed to find the errors.

Was it helpful?

Solution

if (radius = 0) should be if (radius == 0)

OTHER TIPS

This:

#define PI=3.14

Should be this:

#define PI 3.14

Also you have an assignment in if comparison: if (radius = 0), should be if (radius == 0). Moreover, you shouldn't compare float or double like this.

In C, = is an assignment operator, and == a relational one. When you write

if (radius = 0)

you are assigning zero to radius. In C, that assignment is an expression, and has a value. An assignment expression evaluates to the value assigned to the left hand side of expression. In this case, since you're assigning zero, the value of the entire assignment is zero, and

if (radius = 0)

evaluates to zero, or false. As a "side effect" (that's the technical term) of the assignment, radius gets the value zero too. The side effect is, of course, unfortunate and unintended in this case.

So what you want, as others have pointed out, is the relational operator ==:

if (radius == 0)

This too is an expression with a value: it evaluates to true or false, which is what you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top