如何在C语言中用*输出国家奖牌数对应的垂直直方图
实现思路
- 先动态计算直方图高度:遍历奖牌数组获取最大奖牌数,该值即为直方图的总行数,完全不需要硬编码高度,可适配任意奖牌数值
- 逐行打印星号区域:从最高层开始向下遍历每一层,对每个国家判断其奖牌数是否大于等于当前层数,是则输出
*,否则输出等宽空格,每列预留固定宽度保证上下对齐 - 打印底部标注:输出一行分隔线后,按列对齐打印对应国家名称即可
完整C语言实现代码
#include <stdio.h> #include <string.h> int main() { char countryNames[10][100] = {"Japan", "USA", "China", "ROC", "UK", "Australia", "Kosova", "Italy", "France", "Canada"}; int totalMedals[10] = {13, 14, 18, 12, 7, 6, 2, 9, 5, 4}; int countryCount = 10; int colWidth = 10; // 每列宽度,适配最长国名Australia(9字符),可自行调整 int maxMedal = 0; // 计算最大奖牌数,自动确定直方图高度 for (int i = 0; i < countryCount; i++) { if (totalMedals[i] > maxMedal) { maxMedal = totalMedals[i]; } } // 从上到下打印每一行星号 for (int currentLevel = maxMedal; currentLevel > 0; currentLevel--) { // 左侧打印当前层数标注,不需要可以删除此行 printf("%2d |", currentLevel); for (int i = 0; i < countryCount; i++) { if (totalMedals[i] >= currentLevel) { // 星号居中显示 printf("%*c", colWidth/2, '*'); printf("%*c", colWidth - colWidth/2, ' '); } else { printf("%*c", colWidth, ' '); } } printf("\n"); } // 打印分隔线 printf("%2s +", ""); for (int i = 0; i < countryCount * colWidth; i++) { printf("-"); } printf("\n"); // 打印底部国家名称 printf("%2s |", ""); for (int i = 0; i < countryCount; i++) { printf("%-*s", colWidth, countryNames[i]); } printf("\n"); return 0; }
调整说明
如果需要适配更长的国家名称,可以新增逻辑遍历国名数组计算最长名称长度,将colWidth设置为最长长度+2即可自动适配列宽,不需要修改其他逻辑。
内容的提问来源于stack exchange,提问作者Azazel
相关产品推荐
相关产品推荐

