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

问题描述 投票:0回答:1

嘿伙计,所以我有一个问题,可能很简单,我只是想不出一个解决方案。我的函数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;
}
c++ printing switch-statement
1个回答
1
投票

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

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

DEMO

© www.soinside.com 2019 - 2024. All rights reserved.