简体   繁体   English

C中输入数字的平均值-总和始终为0

[英]Average of entered numbers in C - sum always 0

Here is a code which evaluates the average of 10 entered numbers. 这是一个代码,用于评估10个输入数字的平均值。 Problem is it doesn't seem to print the sum correctly (it's always equal to 0) after exiting the loop, everything else is working fine. 问题是退出循环后,似乎不能正确打印总和(始终等于0),其他所有工作都很好。

int count=0, n=10, c;
float sum=0, x;
do{
    printf("x=");
    scanf("%f", &x);
    count++;
    sum+=x;
}
while(count<n);
printf("Sum is %d", sum);
printf("\nCount is: %d", count);
printf("\nThe Average of the numbers is : %0.2f", sum/count);
getch();
}

Another question is how to exit the loop after a symbol is reached(ie without setting a limit to the number of integers to be entered). 另一个问题是到达符号后如何退出循环(即,不对要输入的整数数设置限制)。

Use the %f format specifier for floating point numbers. %f格式说明符用于浮点数。

printf("Sum is %f", sum);

To exit the loop on a symbol, you could check the return value from scanf . 要退出符号循环,可以检查scanf的返回值。 scanf returns the number of items read. scanf返回读取的项目数。 If it returns 0 then the user didn't type a valid number. 如果返回0,则用户未输入有效数字。

while (1) {
    printf("x=");

    if (scanf("%f", &x) != 1) {
        break;
    }

    ...
}

break exits the current loop. break退出当前循环。

To answer your first question it should be printf("%f",sum) to print the correct sum. 要回答您的第一个问题,应使用printf(“%f”,sum)来打印正确的总和。 Since you are using float you have to use %f, if you use int it is %d. 由于使用的是float,因此必须使用%f,如果使用int则为%d。 For your second question, you can do something like this (modify it accordingly): 对于第二个问题,您可以执行以下操作(相应地进行修改):

int main(){ 
// Declare Variables 
int count = 0; float sum = 0, currentNum = 0;

// Ask user for input 
while(currentNum > -1)
{ 
   printf("Enter integer to be averaged (enter -1 to get avg):"); 
   scanf("%f",&currentNum); 
   if(currentNum == -1)
       break; 

   // Check the entered number and computed sum
   printf("You entered: %0.2f\n", currentNum); 
   sum += currentNum; 
   printf("Current sum: %0.2f\n", sum);
   count++; 
}

// Print Average
printf("Average is: %0.2f\n", sum/count); 

return 0; 
}

To answer your second question, you could do this: 要回答第二个问题,您可以这样做:

scanf("%f", &x);
if (x==0) {
  break;
}

This will break you out of the loop if you enter 0, then your loop can be infinite: 如果输入0,这会让您跳出循环,那么循环可以是无限的:

do {

} while(true)

对于第二个问题,我认为EOF可能是更好的解决方案:

while(scanf("%f", &x) != EOF)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM