【问题标题】:Copying from input to the output text file从输入复制到输出文本文件
【发布时间】: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 开始。

标签: c++ file-io primes


【解决方案1】:

问题在于您的素数测试算法,您无法确定一个数字是否为素数,除非您将其除以 [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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 2014-10-18
    相关资源
    最近更新 更多