尝试打印正确的'*'量来代替数值

Trying to print the correct amount of '*' in place of a numeric value

本文关键字:打印      更新时间:2023-10-16

嘿伙计们,所以我有一个问题可能很简单,我想不出解决方案。我的函数 void printRanges,正确检查数组值的范围,并递增数组 int ticker[10]。我想做的是打印出范围以及每个类别中有多少星星*,而不是数字本身。

所以现在我可以打印它,比如:"00:1"等等,但想知道我如何打印出相应数量的星星来代替数字。 如:"00:*"10:**"等。我必须使用一堆 for 循环吗?还是我错过了什么非常简单的东西!

感谢您的帮助!我真的很感激!

#include <iostream>
#include <string>
#include <math.h>
using namespace std;
// declare const variable for array size, and array prototypes
const int SIZE = 20;
void fill(int arr[SIZE]);
void print(int arr[SIZE]);
void printRanges(int arr[SIZE]);
int main() {
    // create an array with 20 components 
    int arr[SIZE] = { 0 };
    // call functions
    fill(arr);
    print(arr);
    printRanges(arr);

    // pause and exit
    getchar();
    getchar();
    return 0;
}
//fills array arr with 20 random numbers
void fill(int arr[SIZE]) {
    for (int i = 0; i < SIZE; i++) {
        arr[i] = rand() % 100;
    }
}
// prints the array
void print(int arr[SIZE]) {
    for (int i = 0; i < SIZE; i++) {
        cout << arr[i] << " ";
    }
}
// finds the range of each value in the array and stores it in the array ticker, then prints
// a list from 00-90 documenting how many values are in each range
void printRanges(int arr[SIZE]) {
    int ticker[10] = { 0 };
    char star = '*';
    for (int i = 0; i < SIZE; i++) {
        switch (arr[i] / 10) {
        case 0:
            ticker[0] = ticker[0] + 1;
            break;
        case 1:
            ticker[1] = ticker[1] + 1;
            break;
        case 2:
            ticker[2] = ticker[2] + 1;
            break;
        case 3:
            ticker[3] = ticker[3] + 1;
            break;
        case 4:
            ticker[4] = ticker[4] + 1;
            break;
        case 5:
            ticker[5] = ticker[5] + 1;
            break;
        case 6:
            ticker[6] = ticker[6] + 1;
            break;
        case 7:
            ticker[7] = ticker[7] + 1;
            break;
        case 8:
            ticker[8] = ticker[8] + 1;
            break;
        case 9:
            ticker[9] = ticker[9] + 1;
            break;
        }       
    }
    cout << endl << "00: " << star;
}

首先,您可以通过简化来消除开关。然后,您需要一个循环来打印范围。

void printRanges(int arr[SIZE]) {
    int ticker[10] = { 0 };
    for (int i = 0; i < SIZE; i++) {
        unsigned int index = arr[i] / 10;
        if (index < 10) {
            ticker[index] += 1;
        }
    }
    for (int i = 0; i < 10; i++) {
        // Print i pre-padded with "0"
        cout << setfill('0') << setw(2) << i << ": ";
        // Print the asterisks
        cout << setfill('*') << setw(ticker[i]) << "" << endl;
    }
}

不要忘记

#include <iomanip>

对于setwsetfill.

演示