c - 求 C 中潜在无限个整数的平均值

标签 c

我需要用 C 语言编写一个程序,读取用户输入的整数,在输入 0 时停止,然后求它们的平均值。
这就是我目前拥有的

int main(void) {

int total, h = -1, sum2 = 0;
float mean;

printf("\nYou've chosen Average.\nEnter the numbers you want to find the average of with a 0 at the end (eg. 2 1 5 12 0)\n");
    scanf(" %d", &total);
    while (total > 0) {
        h++;
        sum2 += total;
        scanf (" %d\n", &mean);
        mean = (float)total / h;                        
    }                   
    printf("Average = %.2f\n", mean);
    return 0;
}

如有任何帮助,我们将不胜感激

更新

int main(void) {

int total, h = 0;
float mean;

printf("\nYou've chosen Average.\nEnter the numbers you want to find the average of with a 0 at the end (eg. 2 1 5 12 0)\n");
    while (scanf (" %d", &total) == 1 && total > 0) {
        h++;
        sum2 += total;  
    }
    mean = (float)total / h;                    
    printf("Average = %.2f\n", mean);
    return 0;
}

最佳答案

基本上你想要的是一个 cumulative moving average ;您可以使用每个新输入值更新平均值。

在伪代码中,它看起来像

cma = 0; // mean is initially 0
n = 0;   // n is number of inputs read so far
while nextValue is not 0
  cma = (nextValue + (n * cma )) / (n + 1)
  n = n + 1
end while

让我们看看它如何处理像 1, 2, 3, 4, 5, 0 这样的序列:

cma = 0;
n = 0
nextValue = 1
cma = (1 + (0 * 0))/(0 + 1) == 1/1 == 1
n = 1
nextValue = 2
cma = (2 + (1 * 1))/(1 + 1) == 3/2 == 1.5 // (1 + 2)/2 == 1.5
n = 2
nextValue = 3
cma = (3 + (2 * 1.5))/(2 + 1) == 6/3 == 2 // (1 + 2 + 3)/3 == 2
n = 3
nextValue = 4
cma = (4 + (3 * 2))/(3 + 1) == 10/4 == 2.5 // (1 + 2 + 3 + 4)/4 == 2.5
n = 4
nextValue = 5
cma = (5 + (4 * 2.5))/(4 + 1) == 15/5 == 3 // (1 + 2 + 3 + 4 + 5)/5 == 3 
n = 5
nextValue = 0

您应该能够相当轻松地将伪代码转换为 C。请记住,整数除法给出整数结果 - 1/2 将产生 0,而不是 0.5。至少有一个操作数必须是浮点类型才能获得浮点结果。您可能需要使用 double 作为输入和结果。

关于c - 求 C 中潜在无限个整数的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42683918/

相关文章:

c - 为什么 C 中没有 "memsize"返回使用 malloc 在堆中分配的内存块的大小?

c - GTK+ 2.24。如何在C中使用unicode符号

c - 将Node插入第一名C编程

c - 显式 int32 -> float32 转换的规则

c - 可以在循环的括号内定义循环变量吗?

c - scanf 没有按预期工作

cublas matrix matrix multiplication 在应用于具有多个 GPU 的一个非常长的维度的矩阵时给出内部错误

C 编程 fscanf

c - memccpy 返回比 src 起始地址更低的内存地址

c - 为 main 外部的结构元素赋值