c++。编写一程序,将随机生成的20个三位整数保存到文件digit.txt中,整数之间使用空格分隔
时间: 2023-12-03 20:43:50 浏览: 202
以下是使用C++编写的程序,可以生成20个随机的三位整数并将它们保存到digit.txt文件中,每个整数之间用空格分隔:
```cpp
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(NULL)); // 设置随机数种子
ofstream outfile("digit.txt"); // 打开输出文件
for (int i = 0; i < 20; i++) {
int num = rand() % 900 + 100; // 生成三位整数
outfile << num << " "; // 写入文件并用空格分隔
}
outfile.close(); // 关闭输出文件
return 0;
}
```
程序中使用了C++的文件输入输出流库,其中ofstream用于打开一个输出文件,<<符号用于向文件中写入数据,close()用于关闭输出文件。同时,使用了C++的随机数生成函数rand()和设置随机数种子的srand()函数。
相关问题
c++编写一程序,将随机生成的20个三位整数保存到文件digit.txt中,整数之间使用空格分隔。
以下是用 C++ 编写的程序,生成20个三位整数并保存到文件 digit.txt 中。
```c++
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
// 随机数种子
srand(time(NULL));
// 生成20个三位整数并保存到文件 digit.txt 中
ofstream outFile("digit.txt");
for (int i = 0; i < 20; ++i) {
int num = rand() % 900 + 100;
outFile << num << " ";
}
outFile.close();
cout << "已将20个随机三位整数保存到 digit.txt 文件中。" << endl;
return 0;
}
```
这个程序使用了 C++ 标准库中的 `fstream` 类和 `rand()` 函数来生成随机数,并将随机数保存到文件中。
c++1.编写一程序,将随机生成的20个三位整数保存到文件digit.txt中,整数之间使用空格分隔。
以下是一种可能的实现方式:
```c++
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
// 设置随机数种子
srand(time(NULL));
// 打开文件
ofstream outfile("digit.txt");
// 生成20个三位整数并写入文件
for (int i = 0; i < 20; i++) {
int num = rand() % 900 + 100; // 生成100~999之间的整数
outfile << num << " ";
}
// 关闭文件
outfile.close();
cout << "已将20个三位整数保存到digit.txt文件中。" << endl;
return 0;
}
```
该程序使用 `srand` 函数设置随机数种子,保证每次运行生成的随机数序列都不同。然后使用 `ofstream` 类型的对象 `outfile` 打开文件 digit.txt,使用循环生成20个三位整数并写入文件,每个整数之间用空格分隔。最后关闭文件并输出提示信息。
阅读全文
相关推荐













