为什么输出0.000000?

时间:2018-04-06 14:22:32

标签: c

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

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;
}

4 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:3)

其他人很好地确定了问题:C是程序性的,并尝试使用peri = (length*2) + (width*2)的值计算length, width

// OP's code with its problem
double length, width, peri = (length*2) + (width*2), area = length*width;

这更加复杂,因为peri = (length*2) + (width*2)当时正在使用未初始化的变量未定义的行为(UB)。 &#34; 0.000000&#34;的输出可能是由于length和/或width在计算时为零,但作为UB,任何事情都可能发生,如代码崩溃,其他输出或谁知道什么。

另一种解决方案:通过创建函数

建立peri = (length*2) + (width*2)的关系
double peri(double length, double width) {
  return (length*2) + (width*2);
}

int main(void) {
  double 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.\n, peri(length, width));
}

答案 2 :(得分:2)

无法保证输出任何内容。您在收到输入之前计算结果。 C将数字存储在变量中;它不使用符号代数。

为了修复您的代码,只需在输入后执行计算。

答案 3 :(得分:-1)

轻松修复:

int main()
{

double length, width, peri, area;

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

////////////////////////////////////
// Now that you have a length and width, do your calculations
////////////////////////////////////
peri = (length*2) + (width*2);
area = length*width;

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


return 0;
}