所以我有一个类的任务,我必须要求用户输入1到3000之间的整数。然后我的程序应该能够判断整数是否是质数。最后,我必须将该整数放入一个文件中,但前提是它是一个素数。但我的问题是我的语法,我不确定它是否正确(很明显,这不是因为我不断收到错误)。是否可以在函数中打开文件?如果是这样,它会成为一个参数? 我一直在阅读我的教科书,并尽可能多地使用Google进行一些指导,但我仍感到迷茫。任何建议都会有帮助。找到素数,然后把素数输入到输出文件
编辑:我的逻辑尽可能的数字工作,但是当我添加代码写入文件,我现在得到错误。
两个误差是
C2440初始化:不能从常数字符转换为int(18行)
C2079 MYFILE:使用未定义class'std :: basic_fstream的<>炭的std :: char_traits> '
这是我的代码到目前为止!
// Project 5.cpp : Defines the entry point for the console application.
//
#include <fstream>
#include "stdafx.h"
#include <iostream>
using namespace std;
//functions
void prime(int x);
//variables
int x=0;
int i;
char answer;
fstream myfile("castor_primes.txt");
int main()
{
do
{
cout << "Enter an integer between 1 and 3000 \n";
cin >> x;
if (x == 1)
{
cout << x << " is not a prime number.\n";
}
else if (x < 1 || x>3000)
{
cout << x << " is an invalid number. \n";
}
else
{
prime(x);
}
cout << "Do you want to enter another number? Y/N \n";
cin >> answer;
} while (answer == 'y' || answer == 'Y');
myfile.close();
return 0;
}
void prime(int x)
{
if (x == 2)
{
cout << "Yes, " << x << " is Prime\n";
}
else
{
for (i = 2; i < x; i++)
{
if (x%i == 0)
{
cout << x << " is not a prime number\n";
break;
}
}
if (x == i)
{
cout << "Yes, " << x << " is Prime\n";
myfile << x ;
}
}
}
只要稍微注意:每个素数是奇数除了2.本呼喊了一些优化... – Garmekain
“其实也很明显这不是因为我不断收到错误” - 嗯......关于发布这些错误怎么办?我在Code :: Blocks上运行你的代码而没有'#include“stdafx.h”',它工作正常。 @Garmekain,关于优化 - 实际上有更多的方法来优化它,但这与问题无关。我极力鼓励你通过使用'outputFile.good()'方法来测试文件打开过程是否成功。如果开放成功,它将返回true。在你发布错误之后,我将着手回答这个问题,并为类似的未来项目提供一些建议。 – Fureeish
@Fureeish这就是为什么它只是一个小记录。 – Garmekain