文件无法打开

File won't open

本文关键字:文件      更新时间:2023-10-16

代码现在运行,但无法打开文件 我也是文件的新手,所以我不知道如何打开文件,但质数有效并给我质数部分,但文件无法打开。

有人知道如何解决这个问题吗?

这是修订后的代码

#include <iostream>
#include <fstream>
using namespace std;
//function prototype
bool isPrime(int number);
int main()
{
//declare variable to store input
//from user
int number;
//declare variable to store
//function output
bool result;
//prompt user to enter his number
//then read from keyboard
cout << "Enter your number, and I will check";
cout << " whether it is prime or not!n";
cin >> number;
//call function and save its output in variable
//passing the user number as argument
result = isPrime(number);
//use if/else statement to determine whether
//to print is prime, or is not prime
if(result)
cout << "The number " << number << " is prime!n";
else
cout << "The number " << number << " is not prime!n";
return 0;
}
bool isPrime(int number)
{
//start checking from 2 onwards
//until number-1, because dividing by 1
//and number will always be evenly divisible
for(int divisor = 2; divisor <= number-1; divisor++)
{
//if an operation up until some point
//returns 0, means that the number if evenly
//divisible by some other number other than
//1 and itself, so return false
if(number % divisor == 0)
return false;
}
//if the whole loop has finished and function has not
//terminated by return statement, it means that number
//is prime so return true
return true;
}
void outputPrimes(int number)
{
//create and open output file
ofstream outputfile("primeNumbers.txt");
cout << "I will write a list of the prime numbersn";
cout << "from 1 to 100 in a file named "primeNumbers.txt"!nn";
//use for loop to call function for numbers
//from 1 to 100
for(int counter = 1; counter < 100; counter++)
{
if(isPrime(counter))
outputfile << counter << endl;
}


//tell user program has terminated and file
//has been written
cout << "File has been written!n";
//return 0 to mark successful termination

//start checking from 2 onwards
//until number-1, because dividing by 1
//and number will always be evenly divisible
for(int divisor = 2; divisor <= number-1; divisor++){
//if an operation up until some point
//returns 0, means that the number if evenly
//divisible by some other number other than
//1 and itself, so return false
if(number % divisor == 0)
}
//if the whole loop has finished and function has not
//terminated by return statement, it means that number
//is prime so return true
}

有没有办法打开文件并给出质数 如果有人能帮忙,那就太好了。

非常感谢


它准确地告诉你问题是什么:你正在重新定义函数bool isPrime(int)的实现。您目前对该函数有三个定义,因此您需要删除其中两个。

编辑:我还将指出这些函数在最后不返回正确的类型。该函数应返回bool但您返回的是int

你正在重新定义(2次(函数bool isPrime(int(的实现。您是否正在尝试实现函数重载。甚至输出也不会正确,因为您返回的是 int 而不是布尔值。从技术上讲,int 将值转换为布尔值,但输出不会像预期的那样。