You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++程序开发需求:24小时气温星号柱状图(支持负值)

C++ Hourly Temperature Bar Chart Generator

Got it, let's tackle this temperature bar chart problem step by step. Here's a complete solution that meets all your requirements, with clear explanations for key parts:

Approach

First, let's break down the problem to keep it manageable:

  • Scale Adjustment: The raw range (-30℉ to 120℉) spans 150 units—way too wide for a terminal. We'll use a scaling factor of 5℉ per asterisk to shrink this to a 30-character width, which fits nicely on most screens.
  • Negative Values: We'll use a vertical bar (|) to mark the 0℉ baseline. Negative temperatures draw asterisks to the left of this bar, positive ones to the right, making negative values instantly recognizable.
  • Clean Formatting: Align all temperature values and bars to keep the chart tidy, plus add a descriptive header to clarify the scale and range.

Complete Code

#include <iostream>
#include <fstream>
#include <vector>
#include <iomanip>
#include <cstdlib> // For abs()

using namespace std;

int main() {
    // Open the temperature data file
    ifstream tempFile("temps.txt");
    if (!tempFile.is_open()) {
        cerr << "Error: Could not open temps.txt file!" << endl;
        return 1;
    }

    // Read 24 hourly temperatures into a vector
    vector<int> temperatures;
    int temp;
    while (tempFile >> temp && temperatures.size() < 24) {
        // Clamp values to the valid range (-30 to 120) to avoid invalid bar lengths
        if (temp < -30) temp = -30;
        if (temp > 120) temp = 120;
        temperatures.push_back(temp);
    }

    // Validate we have exactly 24 data points
    if (temperatures.size() != 24) {
        cerr << "Error: temps.txt must contain exactly 24 hourly temperature values!" << endl;
        return 1;
    }

    // Print chart header
    cout << "=============================================" << endl;
    cout << "        Hourly Temperature Bar Chart         " << endl;
    cout << "        Range: -30℉ to 120℉ | * = 5℉        " << endl;
    cout << "=============================================" << endl;

    // Print each hour's data and corresponding bar
    for (int hour = 0; hour < 24; ++hour) {
        int currentTemp = temperatures[hour];
        int negStars = (currentTemp < 0) ? abs(currentTemp) / 5 : 0;
        int posStars = (currentTemp > 0) ? currentTemp / 5 : 0;

        // Format hour (2-digit) and temperature (aligned for readability)
        cout << setw(2) << setfill('0') << hour << ":00 "
             << setw(4) << setfill(' ') << currentTemp << "℉  ";

        // Print asterisks for negative temperatures (left of baseline)
        for (int i = 0; i < negStars; ++i) {
            cout << "*";
        }

        // Print 0℉ baseline marker
        cout << "|";

        // Print asterisks for positive temperatures (right of baseline)
        for (int i = 0; i < posStars; ++i) {
            cout << "*";
        }

        cout << endl;
    }

    tempFile.close();
    return 0;
}

Key Details Explained

  1. File Handling:

    • The code checks if temps.txt exists and can be opened—if not, it prints a clear error and exits.
    • It reads exactly 24 values, clamping any out-of-range temperatures to -30 or 120 to prevent invalid bar lengths that would break the chart layout.
  2. Scale & Negative Value Logic:

    • We calculate negStars (asterisks for negative temps) and posStars (asterisks for positive temps) using integer division by 5 (our scaling factor). This keeps the chart width manageable.
    • The | character acts as a visual anchor for 0℉, making it easy to compare positive and negative temperature magnitudes at a glance.
  3. Clean Formatting:

    • setw and setfill ensure hours are displayed as two digits (e.g., 00:00 instead of 0:00) and temperatures are aligned, so the chart looks polished and professional.

How to Use

  1. Create a file named temps.txt with 24 integers (one per line, or space-separated), each representing an hourly temperature in ℉.
  2. Compile and run the program—you'll get a formatted bar chart printed directly to your terminal.

Example output snippet:

=============================================
        Hourly Temperature Bar Chart         
        Range: -30℉ to 120℉ | * = 5℉        
=============================================
00:00  -10℉  **|
01:00   20℉  |****
02:00    0℉  |
03:00  -25℉  *****|
...

内容的提问来源于stack exchange,提问作者throwthedays

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:51:27