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

标签 c++

这是作业。

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

相关文章:

c++ - OnMousePress 脚本在 UE4 中不起作用

java - Java 与 C++ 中的基元数组

c++ - 函数原型(prototype)与 C++ 类中的任何原型(prototype)都不匹配

c++ - 无法理解实例变量

c++ - 在 C++ 中为 boost::numeric::ublas::vector 分配多个值

c++ - WIN32 API 项目中的 ReadDirectoryChangesW 错误?

c++ - readdir 排除目录中的某些文件

c++ - 结构数组的初始化

c++ - 如何将OpenCV摄像机旋转 vector 转换为OpenGL旋转 vector ?

c++ - 任何 #include 之前的 "using namespace std;"?