You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用scanf结合输入重定向读取文件至EOF并完成计算?

改用scanf+输入重定向读取文件计算均值的修改方案

原本用fscanf实现了读取文件并计算均值的程序,现在要求必须使用scanf结合输入重定向读取包含1500条数据的输入文件(示例文件含25条数据),且要读取至EOF,以下是修改方案:


原代码(用户提供)

#include <stdio.h>

int read_data(int max)
{

    printf("The number is %d\n", max);
}
double mean (double *x, int n)
{
    double total = 0;
double store = 0 ; 
    for (int i=0 ; i < n; ++i)
    {
        total = store + x[i];
        store=total ;

    }
   double mean2 = (total/n);
    return mean2;
}
int main()
{

    FILE *obk ;
    double arr[MAXIMUM], arr1[MAXIMUM], arr2[MAXIMUM];
    obk = fopen ( "in.txt", "r");

    if (obk == NULL )
    {
        printf(" There is no sucha file");
    }
    int j = 0;
    while(fscanf(obk, "%lf", &arr[j])!=EOF)

    {
        j++;
        count++;
        printf("%d\n",arr[j]);

    }
    read_data( arr,  count);


    double mean1 = mean(arr, count);
    printf("%lf", mean1);
}

示例输入文件in.txt内容

12
23
23
4
54
66
55
44
3
23
67
88

核心修改点

  • 移除所有文件操作代码:删掉FILE*指针、fopen、fscanf,直接用scanf从标准输入读取数据
  • 修复原代码语法/逻辑错误:
    • 定义MAXIMUM常量(设置为1501,足够容纳1500条数据)
    • 声明未定义的count变量
    • 修正read_data函数的参数类型(匹配传入的double数组和计数)
    • 简化mean函数的累加逻辑(无需额外store变量,直接累加total)
    • 修正浮点数输出的格式符(用%lf而非%d)
    • 添加数组越界判断,避免读取数据超出数组容量

修改后的完整代码

#include <stdio.h>

// 定义足够大的数组容量,适配1500条数据
#define MAXIMUM 1501

// 修正函数参数,匹配传入的数组和数据总数
void read_data(double *arr, int count)
{
    printf("读取到的数据总数:%d\n", count);
}

// 简化均值计算逻辑
double mean(double *x, int n)
{
    double total = 0;
    for (int i = 0; i < n; ++i)
    {
        total += x[i];
    }
    return total / n;
}

int main()
{
    double arr[MAXIMUM];
    int count = 0;

    // 用scanf读取标准输入,直到EOF或数组满
    while (count < MAXIMUM && scanf("%lf", &arr[count]) != EOF)
    {
        // 可选:打印读取到的数据,验证正确性
        printf("读取到数据:%lf\n", arr[count]);
        count++;
    }

    if (count == 0)
    {
        printf("未读取到任何数据\n");
        return 1;
    }

    read_data(arr, count);
    double mean_val = mean(arr, count);
    printf("均值为:%lf\n", mean_val);

    return 0;
}

输入重定向使用方法

编译代码后,在命令行通过输入重定向指定数据文件:

# Windows命令提示符
your_program.exe < in.txt

# Linux/macOS终端
./your_program < in.txt

程序会自动从in.txt中读取数据直到文件末尾(EOF),效果和原fscanf实现一致。

内容的提问来源于stack exchange,提问作者Obiick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 08:30:35