2017-03-18 46 views
-1

我正在創建一個程序,以使頻率表的範圍從< = 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

+0

問題是什麼?你有錯誤嗎?崩潰,錯誤的結果?! – Arash

+0

當文本中出現-5時,應該顯示<= 0的頻率爲1,程序改爲顯示<= 0的頻率爲0,其他則爲1(如圖所示) – neX

回答

0

的問題是雙重的。首先,你忘了兩個清零,並在計算元素數後重置緩衝區。其次,您總是會計數低於零且大於10的數字。您應該只在num010時這樣做。

正確的代碼應該是這樣的:

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;