尝试打印正确的'*'量来代替数值
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>
对于setw
和setfill
.
演示
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 在gem5中打印文件中的所有cache_blocks
- 打印数字图案
- Log4cpp:以UTC/GMT时区打印日期
- 如何使用gdb制作一个可以漂亮地打印每个对象的C++函数