为什么用户输入变量导致0-C?

rph*_*101 -10 c variables zero

我是一个非常有经验的Java程序员,具有C++背景,但我只是在我的一个编程课程中开始使用C,这让我很疯狂.这是第一个任务.它应该计算球体的体积或表面积.问题是"半径"等于零,即使用户输入了值."模式"工作得很好,这似乎很奇怪.这是代码:

#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; 
}
Run Code Online (Sandbox Code Playgroud)

知道为什么半径没有正确存储?仅供参考 - 大部分代码都是预先编写的.我只是应该找到错误.

Joh*_*136 5

if (radius = 0) 应该 if (radius == 0)

  • @elmes但你不写`if(0 == radius)`因为它不直观而且是向后的.相反,你努力用该死的`-Wall`来编译你的代码...... (6认同)
  • 这就是为什么你总是可以写`if(0 == radius)`以避免这样的错误;)当你错过一个`=`代码将无法编译 (3认同)