gpt4 book ai didi

C++柱形图反转

转载 作者:行者123 更新时间:2023-11-28 05:38:10 25 4
gpt4 key购买 nike

我很困惑为什么我的列是颠倒的。实际的柱形图(仅星号)需要水平翻转。 (1900年人口为2000人,2040年人口为24000人。)

这是它目前的样子:

Population column chart

24000 **
23000 **
22000 ** **
21000 ** **
20000 ** **
19000 ** **
18000 ** ** **
17000 ** ** **
16000 ** ** **
15000 ** ** **
14000 ** ** ** **
13000 ** ** ** **
12000 ** ** ** **
11000 ** ** ** **
10000 ** ** ** **
9000 ** ** ** ** **
8000 ** ** ** ** **
7000 ** ** ** ** **
6000 ** ** ** ** **
5000 ** ** ** ** ** **
4000 ** ** ** ** ** ** **
3000 ** ** ** ** ** ** **
2000 ** ** ** ** ** ** ** **
1000 ** ** ** ** ** ** ** **
1900 1920 1940 1960 1980 2000 2020 2040

代码如下:

#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;

int main(){
int population_size = 8; //Available for changes.
int year = 1900;
int population[population_size];
bool haveFile = true;

const string inFileName = "people.txt";
ifstream inFile("people.txt"); //Defines input file and opens

cout << "Population column chart" << endl;
cout << endl;


if (inFile){
// cout << "Open of " << inFileName << " was successful.\n";
int count = 0;
while (!inFile.eof()) {
inFile >> population[count];
count++;
if (inFile.eof()) break;}

int min = 1000; //Define minimum y-axis amount
int max = 0; //Initialize max value to 0
for (int i=0; i<count; i++){ //Find the maximum population
if(population[i]> max);
max = population[i];
}
//This block creates the y-axis legend and rows of stars
for (int num = max; num >= min; num = num - 1000){
cout << setw(5) << num << " ";
for (int year_counter = 0; year_counter <= count-1; year_counter++)
if (num <= population[year_counter])
cout << setw(3) << "**" << " ";
cout << endl;
}
//This block creates the x-axis legend
cout << " ";
for (int k = 1; k <= count; k++){
cout << setw(6) << year;
year += 20;
}
}
}

问题出在这段代码中:

for (int year_counter = 0; year_counter <= count-1; year_counter++)
if (num <= population[year_counter])
cout << setw(3) << "**" << " ";

population[0] 应该是 2000 的值,但它是 24000。我的数组以某种方式颠倒了吗?

提前致谢

最佳答案

 if(population[i]> max);
max = population[i];

应该是

 if(population[i]> max)
max = population[i];

试试看。

好的,我想我明白现在发生了什么。您正在尝试打印不同年份的人口。每列本质上是 6 个字符宽("\*\*"setw(3) 中设置,加上 "")。问题是,如果要获取 "**",您只打印该列;否则你什么都不打印。所以所有带有 "\*\*" 的列都挤在左边。

解决方案是始终为每一行打印该列,无论它是否获得 "**":

        for (int year_counter = 0; year_counter <= count - 1; year_counter++)
if (num <= population[year_counter])
cout << setw(3) << "**" << " ";
else //NEW
cout << setw(3) << " " << " "; //NEW

关于C++柱形图反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37759344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com