2014-10-08 25 views
1

所以這個程序會產生一個條形圖(非常基本),顯示過去100年間每20年的人口增長情況。如何在不重複每年for循環的情況下使此簡單代碼更有效?

它按預期工作,但我覺得必須有更有效的循環方式,同時獲得相同的結果,而不是重複每年的for循環。我還希望保持在代碼(介紹對C++)中顯示的電平內的溶液

的People.txt包含以下內容:

這是代碼

#include <iostream> 
#include <iomanip> 
#include <fstream> 

using namespace std; 

int main() 
{ 
    ifstream inputFile; // File stream object 
    int number; 

    // Open the input file 
    inputFile.open("People.txt"); 


    cout << "PRAIRIEVILLE POPULATION GROWTH\n" << "(each * represents 1000 people)\n"; 

    //1910's bar 
    cout << "1910 "; 
    inputFile >> number; 
    for (int i = 1; i < number; i+=1000) 
    { 
     cout << "*"; 
    } 
    cout << endl; 

    //1930's bar 
    cout << "1930 "; 
    inputFile >> number; 
    for (int i = 1; i < number; i+=1000) 
    { 
     cout << "*"; 
    } 
    cout << endl; 

    //1950's bar 
    cout << "1950 "; 
    inputFile >> number; 
    for (int i = 1; i < number; i+=1000) 
    { 
     cout << "*"; 
    } 
    cout << endl; 

    //1970's bar 
    cout << "1970 "; 
    inputFile >> number; 
    for (int i = 1; i < number; i+=1000) 
    { 
     cout << "*"; 
    } 
    cout << endl; 

    //1990's bar 
    cout << "1990 "; 
    inputFile >> number; 
    for (int i = 1; i < number; i+=1000) 
    { 
     cout << "*"; 
    } 
    cout << endl; 

    //2010's bar 
    cout << "2000 "; 
    inputFile >> number; 
    for (int i = 1; i < number; i+=1000) 
    { 
     cout << "*"; 
    } 
    cout << endl; 

    // Close the file 
    inputFile.close(); 

    return 0; 
} 
+0

**提示**只使用兩個循環,其中一個應該被嵌套(其中一個想的?!)......和數組。 – Nawaz 2014-10-08 05:44:24

+0

這屬於代碼審查。我個人不能想出任何真正的方法來簡化它。您可以從括號中刪除語句,它可能看起來更好。實際上,你應該檢查打開文件的錯誤,並確保People.txt中有正確的整數。 (編輯:我可能還沒有理解這個問題。) – 2014-10-08 05:44:44

+0

@EvanCarslake這應該給你一個關於代碼設置顯示簡單的想法。 http://i.imgur.com/8TcpTkh.png – RufioLJ 2014-10-08 05:51:52

回答

2

我覺得你的代碼看起來應該像下面這樣:

#include <iostream> 
#include <iomanip> 
#include <fstream> 

using namespace std; 

int main() 
{ 
    ifstream inputFile; // File stream object 
    int number; 

    // Open the input file 
    inputFile.open("People.txt"); 


    cout << "PRAIRIEVILLE POPULATION GROWTH\n" << "(each * represents 1000 people)\n"; 

    for(int y = 1910; y <= 2010; y += 20) 
    { 
     cout << y << ' '; 
     inputFile >> number; 
     for (int i = 1; i < number; i+=1000) 
     { 
      cout << '*'; 
     } 
     cout << endl; 
    } 

    // Close the file 
    inputFile.close(); 

    return 0; 
} 

另請注意,對於星號,引號(字符串文字)已更改爲單引號(字符文字)。運算符< <這種方式會更高效,因爲它不需要將字符串的指針取消引用實際上意味着它,但它會得到一個適合寄存器的單純字符。

+0

就是這樣。很簡單!謝謝。試圖嵌套它時,我沒有看清楚循環。 – RufioLJ 2014-10-08 06:52:39

1

東西從我的頭頂:

// Without error checking, something like this: 
// Assuming it starts at year 1910, at 20 year intervals 

int number = 0; 
int year = 1910; 

while (inputFile >> number) { 
    cout << year << " "; 

    for (int i = 0; i < number; i += 1000) { 
     cout << "*"; 
    } 

    cout << "\n"; 

    year += 2000;   
} 
相關問題