2016-10-26 58 views
1

因此,我目前正在嘗試創建一個程序,它讀取一個名爲「input.txt」的文件,其整數存儲如下,並計算它們的百分比大於零,小於零,並且等於零。每行讀取整數並顯示百分比

10 
-4 
0 
34 
42 
-2 
0 

這裏是我的代碼:使用命名空間std

;

ifstream inputFile; 
int count = 0; 
int value,negative,positive,zero; 
double negPerc,posPerc,zeroPerc; 

inputFile.open("input.txt"); 
if (!inputFile.fail()){ 

    while (inputFile >> value) 
      { 
      count++; 

      if(value < 0) 
       negative++; 
      if(value == 0) 
       zero++; 
      if(value > 0) 
       positive++; 

      } 

     } 
else 
{ 
    cout << "\nError, unable to open input file "; 
} 

cout << fixed << setprecision(1); 

negPerc = (negative/count)*100; 
posPerc = (positive/count)*100; 
zeroPerc = (zero/count)*100; 


cout << "There were " << negPerc << "% negative numbers." << endl; 
cout << "There were " << zeroPerc << "% numbers equal to zero." << endl; 
cout << "There were " << posPerc << "% numbers greater than zero." << endl; 

和outout:

There were 1864443476.0% negative numbers. 
There were 204178000.0% numbers equal to zero. 
There were 0.0% numbers greater than zero. 

我雙重檢查我的代碼,並試圖診斷爲什麼是這樣,但我找不到任何問題。我究竟做錯了什麼?

+2

這些分區是「int/int」,它將截斷爲「int」。在分區之前將其中一個投到「雙」。例如,你可以把它寫成'(negative * 100.0)/ count;'。這只是一個錯誤。 – BoBTFish

+0

這些都是整數 - 負數和數 - 所以你得到整數除法,這不是你所期望的。 – UKMonkey

+5

此外,在遞增之前,將負數,正數和零初始化爲「0」(就像喲與計數一樣)。用-g -Wall編譯並運行編譯器所抱怨的所有內容。另外,查看「命名空間污染」(停止使用「使用命名空間標準」)。 – Chris

回答

0

這裏是你的代碼,每個人的意見放在一起供你學習。

// Compile with "g++ yourCPPfile.cpp -o yourExecName -g -Wall" 
#include <iostream> 
#include <iomanip> 
#include <fstream> 
using std::ifstream; 
#include <cstdio> 
using std::cout; 

int main() { 
    ifstream inputFile; 
    int count, value, negative, positive, zero; 
    count = negative = positive = zero = 0; 
    double negPerc, posPerc, zeroPerc; 

    inputFile.open("input.txt"); 

    if (!inputFile.fail()) { 
     while (inputFile >> value) { 
      count++; 
      if (value < 0) 
       negative++; 
      if (value == 0) 
       zero++; 
      if (value > 0) 
       positive++; 
     } 
    } 
    else { 
     cout << "\nError, unable to open " << inputFile << "!\n"; 
    } 

    // Stays this way until you setPrecision() to something else. 
    cout << std::setprecision(1); 

    // Troubleshooting!! 
    cout << negative << "\n"; 
    cout << positive << "\n"; 
    cout << zero << "\n"; 
    cout << count << "\n"; 

    // Calculations. 
    negPerc = (negative * 100.0/count); 
    posPerc = (positive * 100.0/count); 
    zeroPerc = (zero * 100.0/count); 

    // Your desired result... 
    cout << "There were " << std::fixed << negPerc << "% negative numbers." << "\n"; 
    cout << "There were " << std::fixed << zeroPerc << "% numbers equal to zero." << "\n"; 
    cout << "There were " << std::fixed << posPerc << "% numbers greater than zero." << "\n"; 
    return 0; 
}