我非常喜歡在C編程的初學者,所以請在這裏幫忙。我試圖編寫一個程序,循環詢問用戶輸入一個數字,如果該數字是正數,則將其添加到總數中,如果是負數,則結束程序並顯示平均值,最低輸入和最高輸入。不幸的是,無論我改變什麼樣的低和高的事物,我總是會得到'低',而高數的負數,請幫助!C編程nan輸出
#include<stdio.h>
int main(void)
{
float input;
float total;
float low;
float high;
float average;
int count=0;
printf("\n\nPlease enter a positive number to continue or a negative number");
printf(" to stop: ");
scanf("%f", &input);
while (input > 0)
{
count = count + 1;
printf("\nPlease enter a positive number to continue or a negative");
printf(" number to stop: ");
scanf("%f", &input);
total = total + input;
if (low < input)
{
(low = input);
}
else
{
(low = low);
}
}
if (input < high)
{
(high = input);
}
else
{
(high = high);
}
average = total/count;
printf("\n\n\nCount=%d",count);
printf("\n\n\nTotal=%f",total);
printf("\nThe average of all values entered is %f\n", average);
printf("\nThe low value entered: %f\n", low);
printf("\nThe highest value entered: %f\n", high);
return 0;
}
用gcc編譯它,並用數字1,5,4測試它,然後經過-1我得到以下輸出
Count=3
Total=8.000000
The average of all values entered is 2.666667
The low value entered: nan
The highest value entered: -1.000000
你可能要初始化變量給出的答案初始化除了改變執行順序。由於您尚未定義低點,因此您在比較低點<輸入點時比較未知點。當你輸入
時也是如此。在C中,默認情況下變量未被初始化。 –