-3
嗨,這裏是我的函數代碼,但它不能正常工作,它應該從input.txt中讀取數字並計算每行中偶數,奇數的總和,然後結合素數(這是正確的),並且還複製所有數字,這是質量output.txt從輸入複製到輸出文本文件
這裏是我的代碼問題是:它複製也不是質數的數字。非常感謝 !!!
#include "stdafx.h"
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream read;
read.open("input.txt");
ofstream write;
write.open("output.txt");
string line;
int even, odd, primeXprime;
if(read.fail())
cout << "Cant open input.txt" << endl;
int x, p = 0;
if(read.is_open())
{
while(read, line)
{
even = odd = 0;
primeXprime = 1;
istringstream sRead(line);
while(sRead >> x)
{
if(x % 2 == 0)
even += x;
if(x % 2 != 0)
odd += x;
for(int i = 2; i <= x; i++)
{
if(x % i == 0)
p++;
if(p == 2)
{
primeXprime *= x;
write << x << " ";
p = 0;
}
else
break;
}
}
cout << "Sum of even numbers are: " << even << endl;
cout << "Sum of odd numbers are: " << odd << endl;
cout << "Sum of prime numbers are: " << primeXprime << endl;
cout << endl;
}
read.close();
write.close();
system("pause");
return 0;
}
}
步驟更換您的整個循環,觀察爲什麼不是質數號碼被打印出來。以數字6爲例,並考慮如何通過你的程序。 – jpw
問題是你的素數檢測算法 – Lrrr
if(p == 1)而不是if(p == 2),因爲你從i = 2開始。 – Dien