【发布时间】:2015-05-09 10:33:58
【问题描述】:
大家好,这里是我的功能代码,但它不能正常工作它应该从 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 为例,想一想它将如何通过您的程序。
-
问题在于您的主要检测算法
-
if (p == 1) 而不是 if (p == 2) 因为你从 i=2 开始。