这是作业。
- 设计并编写一个 C++ 程序,从一个文件中输入一系列 24 小时的温度,并输出当天温度的条形图(使用星星)。 (提示;这是一个输入文件,程序的输出到屏幕)
- 温度应该打印在相应条形的左侧,并且应该有一个标题来给出图表的比例。
- 温度范围应为 -30 至 120 华氏度。因为很难在屏幕上显示 150 个字符,所以应该让每个星代表 3 度的范围。这样,条形图的宽度最多为 50 个字符。
这就是我的。
//Include statements
#include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
//Variable declarations
int count;
float temperature;
float stars;
//Declare and open input file
ifstream inData;
inData.open("temperatures.txt");
//Program logic
cout << "Temperatures for 24 hours:" << endl;
cout <<setw(6) << "-30" << setw(9) << '0' << setw(10) << "30" << setw(10) << "60" << setw(10) << "90" << setw(10) << "120"<< endl;
while (inData >> temperature) {
cout << setw(3) << temperature;
if (temperature < 0) {
count = 0;
stars = round(temperature / 3)*-1;
while (count <= stars) {
cout << std::right<< setw(11)<< '*';
count++;
}
cout << '|';
}
if (temperature > 0) {
count = 0;
stars = ceil(temperature / 3);
cout << setw(12) << '|';
while (count < stars) {
cout << '*';
count++;
}
}
else {
cout << setw(12) << '|';
}
count++;
cout << endl;
}
//Closing program statements
system("pause");
return 0;
}
除了从文件中读取负值外,一切正常。如何排列条形图并从条形图向左输出星星?
这是条形图的示例 this
最佳答案
问题出在语句 cout << std::right<< setw(11)<< '*'
上,里面写了好几颗星,中间总是填满了空白。你似乎误解了std::right
从某种意义上说,它会从右到左“重定向”输出方向。然而它只是修改了填充字符的默认位置,但输出仍然是从左到右书写的。
由于您的刻度总是从 -30 到 +120,我宁愿在这个刻度上运行一个循环并检查当前位置是否在相应的温度范围内。在我看来,这比 std::right
更容易阅读。 -事物。它可能如下所示。
int temperature;
cout << "Temperatures for 24 hours:" << endl;
cout <<setw(6) << "-30" << setw(9) << '0' << setw(10) << "30" << setw(10) << "60" << setw(10) << "90" << setw(10) << "120"<< endl;
while (inData >> temperature) {
cout << setw(3) << temperature;
int tempDiv3 = temperature / 3;
for (int i=-30/3; i<=120/3; i++) {
if (i == 0) {
cout << '|';
}
else if (tempDiv3 < 0 && i >= tempDiv3 && i < 0) {
cout << '*';
}
else if (tempDiv3 > 0 && i <= tempDiv3 && i > 0) {
cout << '*';
}
else {
cout << ' ';
}
}
cout << endl;
}
关于c++ - 在条形图中输出负值,使用星号表示三个值的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49657674/