首页 > 解决方案 > 用于创建 .txt 文件的程序。将随机创建的 100 个整数写入其中。整数之间用空格隔开。在 C++ 中

问题描述

我有这段代码,但它每次在所有编译器中都给出相同的随机数,所以它一定是错误的!

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
    ofstream output;
    output.open("Exercise.txt");   
    srand(time(0));
    int numbers = rand() % 1001;
    for(int i=0;i<100;i++) {
        output<< numbers << " ";
    }
    cout<<"Data appended"<<endl;
    return 0; //Return the value
}

标签: c++

解决方案


要理解你的问题,你需要看看你执行代码的顺序,你必须看看你做了什么,并像计算机在执行代码时一样遵循它。计算机将尝试按以下顺序执行此操作:

  1. 打开文件
  2. 种子随机
  3. 生成号码
  4. 写数字 100 次

问题是您只生成了一次号码。所以基本上,你生成了一个随机数,然后打印了 100 次。你的代码应该做的更像是:

  1. 打开文件
  2. 种子随机
  3. 重复步骤 4-5 100 次
  4. 生成号码
  5. 写号码

要解决您的问题,只需将随机数的分配也放在 for 循环中。你的代码应该和我写的一样,所以你随机播种,然后在 for 循环中,在每次迭代中不断生成新的数字。

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main()
{
    int numbers;
    ofstream output;
    output.open("Exercise.txt");  

    srand(time(NULL));
 
    for(int i=0;i<100;i++) {
        numbers = rand() % 1001;
        output<< numbers << " ";
    }
    cout<<"Data appended"<<endl;
    return 0; //Return the value
}

推荐阅读