[英]Finding the Total Number of Prime Number from a List
目前,我正在開發 C++ 中的一個程序,該程序從文件中讀取數字列表並輸出文件中素數的總數。 我得到了兩次錯誤的 output 並且想知道我做錯了什么。 謝謝您的幫助。
這是代碼:
#include <iostream>
#include <fstream>
using namespace std;
bool isPrime(int);
int main() {
string fileName;
cout << "Please enter file name: ";
getline(cin, fileName);
ifstream fin;
fin.open(fileName);
if (!fin) {
cout << "ERROR opening file" << fileName << "!!!" << endl;
}
int numPrime = 0, x;
if (fin) {
fin >> x;
while (fin >> x) {
if (isPrime(x) == true) {
numPrime += 1;
}
else {
numPrime += 0;
}
}
cout << endl;
cout << "The total number of Prime Numbers is " << numPrime;
}
return 0;
}
bool isPrime(int number) {
for (int divisor = 2; divisor <= number - 1; divisor++) {
if (number % divisor == 0) {
return false;
}
}
return true;
}
我嘗試運行代碼,它只是缺少庫字符串。 您可以將它作為#include <string>
添加到開頭。 您還應該檢查文本文件是否與源文件位於同一目錄中。 此外,請確保您輸入的文件格式為 filename.txt
希望有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.