c++ - 用于创建 .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
}
解决方案
要理解你的问题,你需要看看你执行代码的顺序,你必须看看你做了什么,并像计算机在执行代码时一样遵循它。计算机将尝试按以下顺序执行此操作:
- 打开文件
- 种子随机
- 生成号码
- 写数字 100 次
问题是您只生成了一次号码。所以基本上,你生成了一个随机数,然后打印了 100 次。你的代码应该做的更像是:
- 打开文件
- 种子随机
- 重复步骤 4-5 100 次
- 生成号码
- 写号码
要解决您的问题,只需将随机数的分配也放在 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
}
推荐阅读
- java - 上传到 s3 之前的视频和图像压缩
- mysql - pandas to sql raise mysql raise errorclass(errno, errval)
- python - 我如何绘制浮动列表
- go - SQLMock - 模拟出链式 DELETE 查询
- c# - 如何在不需要文本框的情况下从我的视图模型中使用条形码阅读器获取条形码的值?wpf c#
- python - 通过以下链接从新站点刮取数据
- oauth-2.0 - 在 OpenID 连接授权代码流中使用 PKCE 时我们需要 client_secret 吗?
- python - Python列表json转换为列表
- excel - 使用 excel 中的拖动功能以逗号分隔和顺序增加单元格中的数字
- c - 权重偏左树中的融合操作