从输入复制到输出文本文件

时间:2015-05-09 10:33:58

标签: c++ file-io primes

嗨,大家好,这是我的功能代码,但它不能正常工作,它应该从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;
    }
}

1 个答案:

答案 0 :(得分:0)

问题在于您的Primality Testing算法,在用[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;