0
#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

}

这就是显示的内容。

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.
4

3 回答 3

10

C 程序一次从上到下执行一条指令。您已经计算sum并且average在接受这些数字之前。这评估为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;
}
于 2013-10-12T23:56:28.247 回答
7

请记住,C 在没有循环或条件的函数中从上到下运行。

您创建了 num1、num2 和 num3,每个都为 0,并在输入数字之前找到它们的总和和平均值。

执行以下操作:

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
于 2013-10-12T23:56:39.900 回答
5

您似乎误解了变量定义的用法。这些:

float num1 = 0;
float num2 = 0;
float num3 = 0;
float sum = num1 + num2 + num3;
float average = sum / 3;

不要定义sum读取完成后计算的方式,而是实际使用这些值并在程序调用 first 之前计算sumand 。average0scanf

scanf("%f %f %f", &num1, &num2, &num3);
sum = num1 + num2 + num3;                     // <-- place it here
average = sum / 3;
于 2013-10-12T23:57:46.723 回答