用C语言编写一个程序,反复从标准输入中读取双倍数据,直到没有更多数据可读取,然后打印出平均项目数

用C语言编写一个程序,反复从标准输入中读取双倍数据,直到没有更多数据可读取,然后打印出平均项目数,c,while-loop,double,scanf,C,While Loop,Double,Scanf,我无法打印出输入的项目数和该程序的平均值,我应该使用while循环。你能帮我找出我做错了什么吗 #include <stdio.h> int main(void) { double n; int counter = 0; double sum = 0.0, average; scanf("%lf", &n); while (1 != scanf("%lf", &n)) {

我无法打印出输入的项目数和该程序的平均值,我应该使用while循环。你能帮我找出我做错了什么吗

#include <stdio.h>

int main(void) {
    double n;
    int counter = 0;
    double sum = 0.0, average;
    scanf("%lf", &n);
    while (1 != scanf("%lf", &n)) {
        counter++;
        scanf("%lf", &n);
        sum = sum + n;
        printf("%d", counter);
        average = sum / counter;
        printf("%lf", average);
    }
    return 0;
}
#包括
内部主(空){
双n;
int计数器=0;
双倍和=0.0,平均值;
扫描频率(“%lf”,&n);
而(1!=scanf(“%lf”、&n)){
计数器++;
扫描频率(“%lf”,&n);
sum=sum+n;
printf(“%d”,计数器);
平均值=总和/计数器;
printf(“%lf”,平均值);
}
返回0;
}
这就是它应该看起来的样子

输入:
2.2.4 1.5 1.1 3.3 5.5 Q


输出:
6 2.66666 7

您的代码中有太多冗余:

double n;
int counter = 0;
double sum = 0.0, average;
// you do not need the following initial read
// (see reconstructed while condition)
scanf("%lf", &n);

// replace the following line with "while (1)"
while (1 != scanf("%lf", &n)) {
    // sth like the following if block is to be inserted to check end of input
    if (scanf("%lf", &n) == 0) {
        break;
    }

    counter++; // ok
    // you do not need the following line
    // if block takes care of the input
    scanf("%lf", &n);

    sum = sum + n; // ok
    
    // better pull the remaining lines out of the while loop
    printf("%d\n", counter); // better to insert '\n' here
    average = sum / counter;
    printf("%lf\n", average);  // and here '\n'
}

return 0;
顺便说一句,对于上面的代码,您的输入布局必须是:

2.2
2.4
1.5
1.1
3.3
5.5
Q
一个有效的例子可能是:

int main(void) {
    double n;
    int counter = 0;
    double sum = 0.0, average;

    while (1) {
        if (scanf("%lf", &n) == 0) {
            break;
        }

        counter++;
        sum = sum + n;
    }

    printf("%d\n", counter);
    average = sum / counter;
    printf("%lf\n", average);
    return 0;
}

您应该读取循环中的值,测试
scanf()
是否返回
1
以成功转换,在
循环时更新
计数器
,并在循环结束后输出平均值和计数

以下是修改后的版本:

#包括
内部主(空){
int计数器=0;
双n,和=0.0;
而(扫描频率(“%lf”,&n)==1){
计数器++;
sum=sum+n;
}
如果(计数器==0){
printf(“无值\n”);
}否则{
printf(“%d%f\n”,计数器,总和/计数器);
}
返回0;
}

现在看起来怎么样?为什么有这么多的
scanf
调用?您是否意识到每个
scanf
都将消耗其中一个输入?由于不使用每个
scanf
的结果,一些输入将被丢弃。
while(1!=scanf(“%lf”,&n))
将在输入匹配后立即停止循环。这真的是你想要的吗?我猜你是想做
==
而不是
=
printf
调用可能需要在循环之外。也就是说,结果应该显示在最后。对于
平均值
计算也一样-它只需要在循环外执行一次,而不是每次输入。哦,好的,我知道了,现在我只执行了一次扫描,它显示了进度,我将把打印调用放在循环外,看看它是否还能工作。你的答案有点混乱。显示的代码保留了一些不正确的部分(带有注释),然后添加了一些部分有帮助的代码。最好是提供一个完全有效的解决方案,而不是混合使用错误和更正的代码;但我会的,那也很好。在这种情况下,不要添加/更改原始代码的位。保持原始代码与OP完全相同,然后在代码中添加注释,指出问题所在。这是令人困惑的混合。
if(scanf(“%lf”,&n)==0)
如果在
EOF
之前没有发生转换失败,则无法检测到文件结尾。使用“<代码>”(SCANF(“%LF”,and n)=1)可以考虑检查计数器以避免除以零,但以其他方式进行简短而简单的解决方案。