[英]C - Why is the answer 0.00000, when I try enter 3 numbers for the sum and average?
#include <stdio.h>
int main(int argc, char *argv[])
{
float num1 = 0;
float num2 = 0;
float num3 = 0;
float sum = num1 + num2 + num3;
float average = sum / 3;
printf("Enter three numbers:\n"); //Enter three floats
scanf("%f %f %f", &num1, &num2, &num3); //Assign to num1, num2, num3
printf("The sum of these three numbers is %f.\n", sum);//Print sum
printf("The average of these numbers is %f.\n", average);//Print average
}
This is what is displayed. 这就是显示的内容。
Enter three numbers:
12.0
10.0
12.0
The sum of these three numbers is 0.000000.
The average of these numbers is 0.000000.
C programs execute from top to bottom one instruction at a time. C程序一次从上至下执行一条指令。 You have calculated
sum
and average
before accepting the numbers. 在接受数字之前,您已经计算了
sum
和average
。 This evaluated to sum=0
and average=0
because all three numbers were 0. 由于所有三个数字均为0,因此
sum=0
为sum=0
和average=0
0。
main(int argc, char *argv[]) {
float num1,num2,num3,sum,average;
printf("Enter three numbers:\n"); //Enter three floats
scanf("%f %f %f", &num1, &num2, &num3); //Assign to num1, num2, num3
sum = num1 + num2 + num3;
average = sum / 3;
printf("The sum of these three numbers is %f.\n", sum);//Print sum
printf("The average of these numbers is %f.\n", average);//Print average
return 0;
}
Remember that C runs from top to bottom in a function without loops or conditionals. 请记住,C在没有循环或条件的函数中自上而下运行。
You created num1, num2, and num3, as 0 each, and found their sum and average before inputting the numbers. 您创建了num1,num2和num3,分别为0,并在输入数字之前找到了它们的总和和平均值。
Do as follows: 进行如下操作:
float num1 = 0;
float num2 = 0;
float num3 = 0;
float sum = 0;
float average = 0;
printf("Enter three numbers:\n"); //Enter three floats
scanf("%f %f %f", &num1, &num2, &num3); //Assign to num1, num2, num3
sum = num1 + num2 + num3; //calculate
average = sum / 3;
printf("The sum of these three numbers is %f.\n", sum);//Print sum
printf("The average of these numbers is %f.\n", average);//Print average
You seem to misunderstand the usage of variable definition. 您似乎误解了变量定义的用法。 These:
这些:
float num1 = 0;
float num2 = 0;
float num3 = 0;
float sum = num1 + num2 + num3;
float average = sum / 3;
do not define the way the sum
will be computed after the reading is done, but actually use these values and calculate the sum
and average
to be 0
before the program calls first scanf
. 在读取完成后,并没有定义
sum
计算方式,而是实际使用这些值并在程序调用first scanf
之前将sum
和average
计算为0
。
scanf("%f %f %f", &num1, &num2, &num3);
sum = num1 + num2 + num3; // <-- place it here
average = sum / 3;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.