c++,(1)输入两个整数a,b,请将区间[a, b]中的所有素数写入d:\a.txt文件中; (2)将d:\a.txt文件中的素数一一读取,并显示在屏幕上,每行显示8个素数。
时间: 2023-11-22 18:55:13 浏览: 46
以下是实现该功能的 C++ 代码:
```c++
#include <iostream>
#include <fstream>
using namespace std;
bool isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
void writeToFile(int a, int b) {
ofstream outfile("d:\\a.txt");
for (int i = a; i <= b; i++) {
if (isPrime(i)) outfile << i << endl;
}
outfile.close();
}
void readFromFile() {
ifstream infile("d:\\a.txt");
int cnt = 0, num;
while (infile >> num) {
cout << num << " ";
cnt++;
if (cnt % 8 == 0) cout << endl;
}
infile.close();
}
int main() {
int a, b;
cout << "请输入区间[a, b]的起点和终点:";
cin >> a >> b;
writeToFile(a, b);
cout << "以下是区间[a, b]中的素数:" << endl;
readFromFile();
return 0;
}
```
代码解释:
1. `isPrime` 函数用于判断一个数是否为素数,如果是素数返回 true,否则返回 false。
2. `writeToFile` 函数用于将区间 `[a, b]` 中的素数写入 `d:\a.txt` 文件中。
3. `readFromFile` 函数用于从 `d:\a.txt` 文件中读取素数并输出到屏幕上,每行显示 8 个素数。
4. `main` 函数用于获取输入的区间 `[a, b]`,然后调用 `writeToFile` 函数将素数写入文件,最后调用 `readFromFile` 函数输出素数。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)