Visual c++ 60点CMPT Sci

Visual c++ 60点CMPT Sci,visual-c++,visual-studio-2019,Visual C++,Visual Studio 2019,编写一个程序,首先生成[11,25]范围内的100个随机数,并将它们存储在名为“random.txt”的文件中。每行只写一个数字。然后打开并读取文件“random.txt”中的数据。计算所有100个数字的平均值,并计算数字16出现的次数。在此步骤中仅使用一个循环。也就是说,在循环的每次重复期间更新运行总数和16的出现次数。下面给出了示例文件和输出 提示:要生成[min,max]范围内的随机整数,请使用以下语句 rand()%(最大最小值+1)+最小值 >编写一个程序,首先生成[11,25]范围内

编写一个程序,首先生成[11,25]范围内的100个随机数,并将它们存储在名为“random.txt”的文件中。每行只写一个数字。然后打开并读取文件“random.txt”中的数据。计算所有100个数字的平均值,并计算数字16出现的次数。在此步骤中仅使用一个循环。也就是说,在循环的每次重复期间更新运行总数和16的出现次数。下面给出了示例文件和输出

提示:要生成[min,max]范围内的随机整数,请使用以下语句

rand()%(最大最小值+1)+最小值


>编写一个程序,首先生成[11,25]范围内的100个随机数,并将其存储在名为“random.txt”的文件中。

C++提供了以下类来执行文件中字符的输出和输入: ofstream:要在文件上写入的流类 ifstream:从文件读取的流类 fstream:读取和写入文件的流类

我建议您可以尝试使用ofstream将随机数写入“random.txt”文件

代码如下:

    cout << "Now writing data to the file." << endl;
    ofstream OutFile("random.txt");
    for (int i = 0; i < 100; i++)
    OutFile << rand() % (25 - 11 + 1) + 11 << '\n';
    OutFile.close();
    cout << "Done with the writing." << endl;
    cout << "Now reading deta fron the file." << endl;
    int n, r;
    double d, sum;
    FILE *f;
    fopen_s(&f,"random.txt", "r");
    n = 0;
    sum = 0.0;
    while (1) {
        r = fscanf_s(f, "%lf", &d);
        if (1 == r) 
        {
            sum += d;
            n++;
        }
        else if (0 == r) {
            fscanf_s(f, "%*c");
        }
        else break;
    }
    fclose(f);
    cout << "average value=" << sum / n << endl;
cout
    int sum1 = 0;
    ifstream infile("random.txt");
    int number;
    infile >> number;
    while (!infile.eof())
    {
        if (number == 16)
        {
            sum1++;
        }
        infile >> number;
    }
    cout << "The number 16 appears " << sum1 << " times in the file" << endl;