使用星号在条形图中输出负值,以表示三个值的范围

Output negative values in a bar chart using stars to represent a range of three values

本文关键字:表示 范围 三个 条形图 输出      更新时间:2023-10-16

这是作业。

  1. 设计和编写一个C++程序,该程序从文件中输入一系列 24 小时温度,并输出当天温度的条形图(使用星星(。(提示;这是一个输入文件,程序的输出进入屏幕(
  2. 温度应打印在相应条形的左侧,并且应该有一个标题来给出图表的比例。
  3. 温度范围应为 -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;
}