偶数,奇数,素数

时间:2015-04-30 11:34:57

标签: c++

我从读取文件中找到了偶数,奇数,素数

int _tmain(int argc, _TCHAR* argv``[])
{
    ifstream read;
    read.open("input.txt");
    ofstream write;

    write.close();
    read.close();
    system("pause");
    return 0;
}

2 个答案:

答案 0 :(得分:1)

问题是你在迭代之间保持求和变量的状态 避免这种情况的最佳方法是将变量声明并初始化为尽可能接近其使用。

如果您想逐行求和,请使用逐行求和:

   while (getline(read, line)){
        int even = 0;
        int odd = 0;
        int x = 0;
        istringstream sRead(line);
        while (sRead >> x){
            // ...
        }
    }

答案 1 :(得分:0)

while (getline(read, line)){
    even = odd = 0;
    istringstream sRead(line);
    while (sRead >> x){
        if (x % 2 == 0){
            even += x;
        }
        if (x % 2 != 0){
            odd += x;
        }
    }
    write << "Sum of even numbers is: " << even << endl;
    write << "Sum of odd numbers is: " << odd << endl;
}

在每次循环迭代中,您都缺少将evenodd设置为0。