-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