代码之家  ›  专栏  ›  技术社区  ›  antimage64

在C中使用While和do While循环求5个数和N个数的平均值

  •  -1
  • antimage64  · 技术社区  · 7 年前

    我必须编写一个程序,输入5个介于1到10之间的数字,然后计算平均值,只使用WHILE循环,但当数字不满足要求时,它不必退出。然后,我必须编写相同代码的变体,但这次你可以输入你想要的所有数字,当输入0时,它必须计算平均值并退出

    这就是我到目前为止取得的成绩

    #include <stdio.h>
    
    int main(void)
    {
        int n, i = 1;
        float add;
        float avg;
    
        do
        {
            printf("enter the number %d:\n", i++);
            scanf("%d", &n);
            add = add + n;
        } while(n > 0 && n < 11);
    
        avg= (add / 5);
    
        printf("%.1f", avg);
    
        return 0;
    }
    

    1 回复  |  直到 7 年前
        1
  •  2
  •   woz    7 年前

    首先,你正在使用 n 作为您的 while 循环将在第一次交互时退出。使用您的 i 变量,并在每次执行循环时增加它。

    do{
        ...
    }while(i <= 5);
    

    printf("enter the number %d:\n", i); //do not increment it here!
    scanf("%d",&n); //assuming "n" as your variable to scan
    if(n > 0 && n < 11){
        add += n;
        i++; //increment it here instead!
    }
    

    float add = 0;
    float avg = 0;
    int i = 1;
    

    最后,分配您的结果(不是强制性的,但由于您正在使用它,我将保留它):

    avg = add/5.0f
    

    printf("%.1f", avg);