C编程输出平均值

Output the average in C programming

我写了一个程序,让你输入数字并输出平均值。有时它没有输出确切的答案,我不确定为什么。例如,当我输入 1、2、10、-3 时,它输出 2,但它应该输出 2.50。另外,有没有办法通过输入诸如 N 而不是 0 之类的字母来使其跳出循环?这是我的代码:

#include<stdio.h>

int main(){
    int nA = 1;
    int nSum = 0;
    int input = 0;
    double dAvg = 0;
    int nums = 0;
    printf("enter numbers to find the average\n");
    printf("enter 0 to quit.\n");
    while (nA !=0) {
        scanf("%d", &input);
        nA = input;
        nSum+=nA;
        if (nA !=0) {
            nums = nums + 1;
        }
        dAvg = nSum / nums;
    }   
    printf("your average is %lf\n", dAvg);    
    return 0;  
}

你除整数,你应该做双除法:

dAvg = nSum / (double)nums;

只需将除法参数转换为 double:

dAvg = (double) nSum / nums;

必须这样做,因为 nSumnums 都是 int,它们经过 整数除法 ,即小数部分被截断或除法运算符 returns 和 int。因此,为了避免这种情况,我们必须在除法中显式地转换 double

除法运算符得到两个 int 作为操作数,因此它是 returns 一个 int。通过添加小数点,结果隐式转换为 float。如果你想要 float 除法,你应该至少将两个操作数之一提供给除法运算符 float.

It isn't outputting the exact answer sometimes and I'm not sure why.

这行代码是罪魁祸首:

dAvg = nSum / nums

当您输入 1、2、10、-3 时,您应该得到 2.5,但结果的小数部分被截断了。相反,你应该做 double 除法:

dAvg = double(nSum) / nums

Also, is there a way to get it to break out of the loop by inputting a letter such as N instead of 0?

是的,有。您可以使用 C 函数 scanf_s:

char input; // use a char instead of an int
do {
    scanf_s("%c", input, 1);
    if (input == 'N') {
        break;
    }

    nA = input - '0'; // convert char input to int value
    nSum+=nA;
    nums = nums + 1;
    dAvg = nSum / nums;
}
#include<stdio.h>

int main(void) {
   int count = 0, nSum = 0;
   char input = 0;
   double dAvg;
   while(scanf("%c", &input) != -1) { // while not error
      if(input == 'N') break; // go out of loop, you can do it another way:
      // while (scanf("%c", &input) != -1 && input != 'N') {
      if(input != 0) { // If you don't want to count zeros
         nSum += input - '0';
         ++count; // increment by one
      }
   }
   // Here you can check internal errors
   if(count != 0) dAvg = nSum * 1.0 / count;
   printf("%f\n", dAvg); // print double

}

内部类型 char 只不过是简单的数字(如果无符号则为 0-255)。所有符号实际上都是代码,即数字。这就是为什么您可以像处理数字一样使用 char:

char a = 'c';
int b = a + 4;