从文本文件中计算负数以生成频率表时出错

时间:2017-03-18 05:34:22

标签: c++ visual-c++

我正在创建一个程序,使文本文件的频率表范围从< = 0到> = 10整数。但是,当我运行该程序时,如果它包含< = 0或> = 10的数字,则所有其他数字相加,但不计算负数。我认为我的问题在于我的If语句,但我不知道如何纠正它。这是我的代码:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ifstream abc("beef.txt");
int num;
int tem;
int N;
int noNum = 0;
cout << "Class" << "    |   " << "Frequency" << endl;
cout << "_________|___________" << endl;
while (abc >> tem) {
    noNum++;
}
for (num = 0; num < 11; num++) {
    N = 0;
    while (abc >> tem) {
        if (num == tem) {
            N = N + 1;
        }
        if (tem < 0) {
            N = N + 1;
        }
        if (tem > 10) {
            N = N + 1;
        }       
    }
    abc.clear();             //clear the buffer
    abc.seekg(0, ios::beg);  //reset the reading position to beginning
    if (num == 0) {
        cout << "<=0" << "      |      " << N << endl;
    }
    else if (num == 10) {
        cout << ">=10" << "     |      " << N << endl;
    }
    else {
        cout << "  " << num << "      |      " << N << endl;
    }
}
cout << "The number of number is: " << noNum << endl;
}

例如,如果文本文件中有-5,则程序将像this

一样运行

1 个答案:

答案 0 :(得分:0)

问题是双重的。首先,在计算元素数量后,您忘记了两个清除并重置缓冲区。其次,您始终将数字设置为小于零且大于10.您只应在num分别为010时执行此操作。

正确的代码应如下所示:

ifstream abc("beef.txt");
int num;
int tem;
int N;
int noNum = 0;
cout << "Class" << "    |   " << "Frequency" << endl;
cout << "_________|___________" << endl;
while (abc >> tem) {
    noNum++;
}
for (num = 0; num < 11; num++) {
    abc.clear();             //clear the buffer
    abc.seekg(0, ios::beg);  //reset the reading position to beginning
    N = 0;
    while (abc >> tem) {
        if (num == tem) {
            N = N + 1;
        }
        if (tem < 0 && num == 0) {
            N = N + 1;
        }
        if (tem > 10 && num == 10) {
            N = N + 1;
        }
    }
    if (num == 0) {
        cout << "<=0" << "      |      " << N << endl;
    }
    else if (num == 10) {
        cout << ">=10" << "     |      " << N << endl;
    }
    else {
        cout << "  " << num << "      |      " << N << endl;
    }
}
cout << "The number of number is: " << noNum << endl;