从输入复制到输出文本文件
Copying from input to the output text file
大家好,这是我的功能代码,但它不能正常工作,它应该从 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;
}
}
问题出在您的素数测试算法上,您无法确定一个数是否为素数,除非您将它除以 [2,Sqrt(n)] 范围内的所有数字
在行“if(p == 2)”中,您假设它不会除以范围内的任何数字。
将整个 for 循环替换为
for(int i = 1; i < x; i++)
{
if(x % i == 0)
p++;
}
if(p < 2)
{
primeXprime *= x;
write << x << " ";
}
p = 0;
大家好,这是我的功能代码,但它不能正常工作,它应该从 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;
}
}
问题出在您的素数测试算法上,您无法确定一个数是否为素数,除非您将它除以 [2,Sqrt(n)] 范围内的所有数字
在行“if(p == 2)”中,您假设它不会除以范围内的任何数字。
将整个 for 循环替换为
for(int i = 1; i < x; i++)
{
if(x % i == 0)
p++;
}
if(p < 2)
{
primeXprime *= x;
write << x << " ";
}
p = 0;