如何在不重复每年for循环的情况下提高这个简单代码的效率?

时间:2014-10-08 05:37:43

标签: c++

因此,该计划产生一个条形图(非常基本),显示过去100年间每20年一次的人口增长。

它按预期工作,但我觉得必须有一种更有效的循环方式,同时获得相同的结果,而不是每年重复for循环。我还想将解决方案保持在代码中显示的级别(C ++简介)

People.txt包含以下内容:

  

2000 4000 5000 9000 14000 18000

这是代码

#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;
}

2 个答案:

答案 0 :(得分: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;
}

另请注意,引号(字符串文字)已更改为星号的单引号(字符文字)。运算符&lt;&lt;这种方式会更高效,因为它不需要取消引用字符串文字实际意味着指针,但它只是一个适合寄存器的字符。

答案 1 :(得分: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;          
}