如何在不重复每年的for循环的情况下使这个简单的代码更加高效

How can I make this simple code more efficient without repeating the for loops for each year?

本文关键字:简单 代码 高效 情况下 for 循环      更新时间:2023-10-16

因此,该程序生成了一个条形图(非常基本),显示了过去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 GROWTHn" << "(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;
}

我认为您的代码应该如下所示:

#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 GROWTHn" << "(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;这样会更有效,因为它不需要取消引用字符串字面意思的指针,但它只得到一个适合寄存器的字符。

我脑海中浮现的东西:

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