将前100个素数打印到文件中

时间:2015-10-28 17:51:58

标签: c++

我必须使用我们之前写过的函数将1-100中的素数列表写到文件中。注释掉的部分不是任何相关的;它只是我们用于函数的先前代码。我不确切知道发生了什么,因为文件甚至没有被创建,for循环中的部分只执行2次,100次。

#include <iostream>
#include <fstream>

using namespace std;

bool isPrime(int);

int main () {

ofstream outputFile;
int p = 2;

cout << "I will be giving you the first 100 prime numbers " << endl;
cout << "And giving you a file containing those numbers." << endl;

outputFile.open("PrimeNumbers100.txt");

        for (int i = 2; i <= 100; i++) 
        {

            isPrime(p);
            cout << p << endl;
            outputFile << p << endl;

        }

outputFile.close();
cout << "You should now have the file." << endl;

/* int n;
int counter = 0;
int p = 2;

cout << "Welcome to prime counter. " << endl;
cout << "Which prime number would you like? ";
cin >> n;

while (counter < n) {
        if (isPrime(p)) {
        counter++;
    }
    p++;
}
p = p - 1;
cout << "Prime number " << n << " is " << p << "." << endl;
*/

return 0;
}

bool isPrime(int p) {

bool result = true;

if (p < 2) {
    result = false;
}
else {
    int stop = (int) (sqrt(p + .5));
    for (int d = 2; d <= stop; d++) {
        if (p % d == 0) {
            result = false;
            break;
        }
    }
}

return result;
}

有人可以解释我在这里做错了什么,为什么它甚至没有创建文件?

3 个答案:

答案 0 :(得分:0)

您使用p在顶部初始化2。您应该使用isPrime来调用i

答案 1 :(得分:0)

您正在获取2,因为您正在打印并存储p,但循环已超过i

答案 2 :(得分:0)

这是更新的代码。经过研究,我确实找到了保存文件的位置,并且有些实例根本没有工作。但是,这段代码运行并确实给了我所需要的一切......感谢您的提示,我非常感谢....建设性的反馈。

#include <iostream>
#include <fstream>

using namespace std;

bool isPrime(int);

int main () {

ofstream outputFile;

cout << "I will be giving you the first 100 prime numbers " << endl;
cout << "And giving you a file containing those numbers." << endl;

outputFile.open("PrimeNumbers100.txt");


        for (int i = 2; i <= 100; i++) 
        {
            if (isPrime(i)) {
            outputFile << i << endl;
            }

        }

outputFile.close();
cout << "You should now have the file." << endl;

return 0;
}

bool isPrime(int p) {

bool result = true;

if (p < 2) {
    result = false;
}
else {
    int stop = (int) (sqrt(p + .5));
    for (int d = 2; d <= stop; d++) {
        if (p % d == 0) {
            result = false;
            break;
        }
    }
}

return result;
}