编写程序lx1.cpp实现求取1-100之间的质数,通过文件输出流对象将结果保存在文件data1.txt中。
时间: 2023-04-22 13:05:30 浏览: 96
好的,以下是程序lx1.cpp的代码实现:
```c++
#include <iostream>
#include <fstream>
using namespace std;
bool isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
int main() {
ofstream fout("data1.txt");
for (int i = 1; i <= 100; i++) {
if (isPrime(i)) {
fout << i << " ";
}
}
fout.close();
return 0;
}
```
程序的主要思路是,先定义一个函数isPrime用来判断一个数是否为质数,然后在主函数中遍历1到100之间的所有数,对于每个数,如果它是质数,就将它输出到文件data1.txt中。最后关闭文件输出流对象即可。
希望对您有帮助!
相关问题
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4 at LX1.S8.main(S8.java:12)
This error message indicates that an array index was accessed that is outside the bounds of the array. In this case, the array has a length of 4, but the code is trying to access the element at index 4, which does not exist. To fix this error, you need to make sure that you only access valid indices of the array, which range from 0 to the length of the array minus 1.
阅读全文