为什么输出0.000000?

Alt*_*ton -1 c

有人可以解释为什么这两个变量"area"和"peri"输出0.000000?

int main()
{

    double length, width, peri = (length*2) + (width*2), area = length*width;

    printf("Enter the length of the rectangle in centimeters: ");
    scanf("%lf", &length);
    printf("\nEnter the width of the rectangle in centimeters: ");
    scanf("%lf", &width);

    printf("The perimeter of the rectangle is %lf cm.\nThe area of the rectangle is %lf cm.", circ, area);


    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*vie 5

Aton,看起来如果要为变量赋一个表达式,并认为每次表达式的变量发生变化时都会计算表达式.

这在excel中是如此,但在C.

在C中,您指定将在程序流/序列通过代码时执行的计算.所以在C中你会写:

int main()
{
        double length, width, peri, area;

    printf("Enter the length of the rectangle in centimeters: ");
    scanf("%lf", &length);
    printf("\nEnter the width of the rectangle in centimeters: ");
    scanf("%lf", &width);
    peri = (length*2) + (width*2);  // <== perform calculations only now
    area = length*width;
    printf("The perimeter of the rectangle is %lf cm.\nThe area of the rectangle is %lf cm.", peri, area);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 我赞成这样的答案,因为它不仅解释了代码的错误以及如何纠正它,而且它识别并解决了提问者可能有的错误想法.修正一个错误的想法,以便提问者可以自己正确推理比仅仅修复错误的代码更有价值. (3认同)