如何在不重复每年的for循环的情况下使这个简单的代码更加高效
How can I make this simple code more efficient without repeating the for loops for each year?
因此,该程序生成了一个条形图(非常基本),显示了过去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;
}
相关文章:
- boost::spirit--试图编译大多数简单代码的编译器错误
- 奇怪的 G++ 错误,带有关于左值和赋值的简单代码
- 为什么 for 循环只接受这个简单代码中的最后一个字符串?
- SFML C 为什么在屏幕上没有绘制?(简单代码)
- GoogleMock发出用Eclipse构建C 的简单代码
- 为什么我的简单代码在C++中不起作用?
- PQXX简单代码崩溃了
- 此简单代码的正统代码
- 我在C++文件中的简单代码块上有 2 个错误。错误 C2059:语法错误:"?"。第二智能感知:预期表达式。怎么了?
- 用谷歌基准测试简单代码的问题
- 简单代码给出C 错误C4430和C2143
- 这个带有向量的简单代码有什么问题?
- 优化项目Euler 16的简单代码
- 如何重写此 C++ 简单代码
- 是否有Visual c++编译器在线,以及如何在c++和vs简单代码之间转换
- 简单代码问题-未定义标识符
- OpenCV简单代码编译成功,但在运行时崩溃
- 如何在另一个类中构造一个类?(简单代码)
- 验证给定C++编译器是否将源代码读取为 C++11 的快速简单代码是什么?
- 带有类的 C++ 简单代码