簡體   English   中英

C-為什么當我嘗試輸入3個數字作為總和和平均值時,答案為0.00000?

[英]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

}

這就是顯示的內容。

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程序一次從上至下執行一條指令。 在接受數字之前,您已經計算了sumaverage 由於所有三個數字均為0,因此sum=0sum=0average=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;
}

請記住,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

您似乎誤解了變量定義的用法。 這些:

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

在讀取完成后,並沒有定義sum計算方式,而是實際使用這些值並在程序調用first scanf之前將sumaverage計算為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM