2015-09-26 41 views
-2
#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

int main(){ 

    int ranking = 0; 
    int population = 0; 
    float leadingNumPercent = 0; 
    float oneCounter = 0; 
    float twoCounter = 0; 
    float threeCounter = 0; 
    float fourCounter = 0; 
    float fiveCounter = 0; 
    float sixCounter = 0; 
    float sevenCounter =0; 
    float eightCounter =0; 
    float nineCounter =0; 
    float overAllCounter =0; 
    int i =0; 
    string countryName; 
    ifstream inFile; 

    inFile.open("test.txt"); 

    while(!inFile.eof()){ 
     inFile >> ranking; 
     inFile >> population; 
     getline(inFile, countryName); 

    while (population >= 10) { 
     population = (population/10); 

    } 

    if (population < 10){ 
     if (population == 1){ 
     oneCounter++; 

     return oneCounter; 

     }  
     if (population == 2){ 
     twoCounter++; 
     return twoCounter; 
     } 
     if (population==3){ 
     threeCounter ++; 
     return threeCounter; 
     }  
     if (population==4){ 
     fourCounter ++; 
     return fourCounter; 
     }  
     if (population==5){ 
     fiveCounter ++; 
     return fiveCounter; 

     }  
     if (population==6){ 
     sixCounter ++; 
     return sixCounter; 
     }  
     if (population==7){ 
     sevenCounter ++; 
     return sevenCounter; 
     }  
     if (population==8){ 
     eightCounter ++; 
     return eightCounter; 
     }  
     if (population==9){ 

     nineCounter ++; 
     return nineCounter; 
     } 




    } 
    leadingNumPercent = (oneCounter/238)*100; 
    cout << leadingNumPercent; 

} 
    inFile.close(); 





    return 0; 


} 

這裏是test.txt文件,我鏈接到http://www.buildingthepride.com/faculty/jajerkins/cs155-01/population2014.txt。它似乎不會進入if(人口< 10){if(population == 1)循環。我使用cout進行了檢查,人口正在減少到一位數我不知道爲什麼我的程序沒有進入循環

+1

'我用cout檢查過了'你有'return oneCounter; cout << oneCounter;'return之後的語句當然不會運行。 –

+0

,因爲人口有價值0 –

+0

我改變了一個計數器的回報,它正在進入循環,但是當我離開if循環並嘗試使它成爲一個百分比時,它出現空白,當我cout –

回答

1

是的,return是原因。

還讓我幫你解決你的代碼。

1.-檢查​​是否小於10是否真的有意義?如果您希望避免不合邏輯的錯誤,請將其與負值進行比較,並在用戶在文本文件中指出該錯誤時提醒用戶。隨着while (population >= 10)你迫使價值變成<比10.

2.-爲什麼要做所有複雜的比較?如何:

int counter[10]; 
counter[population-1]++; 

while (population >= 10) { 
    population = (population/10); 
} 

,而不是使用所有這些如果和一次又一次比較​​。

3.-爲什麼你使用return呢?你打破了整個計劃。 inFile.close()也不會這樣發生。如何:

for(int i=0 ; i<10 ; i++) 
{ 
    cout << "Number " << i << ": " << counter[i] << std::endl; 
} 
行後

inFile.close(); 

4.-如果你想測試一些價值,爲什麼不breakwhile(!inFile.eof())循環,讓cout告訴你的變量。如果您確實是整數,請不要使用float。由於您正在計算數量,請使用int或更好,然後unsigned int

+0

即時通訊仍然開始學習C++和我真的不是什麼 int counter [10]; counter [population-1] ++; 呢。我取消了回報,並且工作更好一些。 –

+0

很高興知道,如果你練習,我相信你會變得更好。 –

+0

我實際上已經掌握了它的工作(儘可能多地完成任務),並且將努力獲得一個for循環並處理大量的if。感謝您的幫助 –

相關問題