使用星号在条形图中输出负值,以表示三个值的范围
Output negative values in a bar chart using stars to represent a range of three values
这是作业。
- 设计和编写一个C++程序,该程序从文件中输入一系列 24 小时温度,并输出当天温度的条形图(使用星星(。(提示;这是一个输入文件,程序的输出进入屏幕(
- 温度应打印在相应条形的左侧,并且应该有一个标题来给出图表的比例。
- 温度范围应为 -30 至 120 F .由于很难在屏幕上显示 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;
}
除了从文件中读取负值外,一切都有效。如何排列条形图并从条形图向左输出星星?
下面是条形图应如下所示的示例
问题出在语句 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;
}
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 表示"accepting anything for this template argument" C++概念的通配符
- 尝试通过多个向量访问变量时,向量下标超出范围
- 错误:未在此范围内声明'reverse'
- 如何将ampl中的集合表示为c++中的向量
- 正在将指针转换为范围
- 使用std::transform将一个范围的元素添加到另一个范围中
- 在基于范围的for循环中使用结构化绑定声明
- std::is_base_of表示ctor编译错误
- 输入中的字符串数未知(以字母表示)
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 如何计算数据类型的范围,例如int
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 在C++中查找范围的长度
- 使用星号在条形图中输出负值,以表示三个值的范围
- 如何获得从负无穷大到无穷大的范围以在 0 到 1 的范围内表示
- 表示范围所需的位的编译时计算
- 当传递表示负值的十六进制时,C++stoll抛出超出范围的异常
- 32位,64位和80位浮点IEEE-754的可表示值范围
- 如何在c++中表示数组位置的范围