【发布时间】:2017-07-07 23:34:16
【问题描述】:
所以我有一个班级作业,我必须向用户询问 1 到 3000 之间的整数。然后我的程序应该能够判断该整数是否为质数。最后,我必须将该整数放入文件中,但前提是它是质数。但我的问题是我的语法,我不确定它是否正确(实际上显然这不是因为我不断收到错误)。是否可以在函数中打开文件?如果是这样,它会成为一个参数吗? 我一直在阅读我的教科书并尽可能多地搜索一些指导,但我仍然感到迷茫。任何建议都会有所帮助。
编辑:就数字而言,我的逻辑是有效的,但是当我添加要写入文件的代码时,我现在遇到了错误。
这两个错误是
C2440 初始化:无法从常量 char 转换为 int(第 18 行)
C2079 myfile: 使用未定义的类'std::basic_fstream char,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 外,每个素数都是奇数。这需要一些优化...
-
“实际上显然这不是因为我不断收到错误” - 嗯......发布这些错误怎么样?我在没有
#include "stdafx.h"的情况下在 Code::Blocks 上运行了您的代码,它运行良好。 @Garmekain,关于优化-实际上有更多优化方法,但这与问题无关。我强烈建议您使用outputFile.good()方法测试文件打开过程是否成功。如果打开成功,则返回 true。在您发布错误后,我将继续回答问题并为类似的未来项目提供一些建议 -
@Fureeish 这就是为什么它只是一个小便条。
-
仅供参考,如果将答案转换为小写或大写,则只需进行一次比较。见
std::toupper和std::tolower。 -
在没有
stdafx.h标头的 GCC 中为我工作,如果行为是输入数字并且如果它是素数,则将其写入castor_primes.txt文件的第一个位置(如果没有则创建它不存在)。正如@Fureeish 指出的那样,您应该发布您遇到的错误。
标签: c++ function file-io output primes