思考:我们可以在控制台输出数值,也能进行计算或者打印我们想要的一句话,那么这位“朋友”有没有别的本领?嘿嘿:自然是有介绍这位朋友的另一个本事——画图
上才艺!先说好:这里我用的while循环
如果你有更好的见解,欢迎在评论区留言,讨论!
先来画个9*9乘法表,需要注意一下几点
- 双重循环结构(外层控制行,内层控制列)
- 格式化输出对齐
- 指针遍历代替数组下标访问
- 使用三元运算符处理特殊情况
#include <stdio.h>
#define SIZE 9
int main() {
// 定义行指针和列指针
int (*p_row)[SIZE] = NULL;
int *p_col = NULL;
int results[SIZE][SIZE];
// 使用指针填充乘法表结果
p_row = results;
int i = 1;
while (i <= SIZE) {
p_col = *(p_row + i - 1);
int j = 1;
while (j <= SIZE) {
// 使用指针存储计算结果
*(p_col + j - 1) = i * j;
j++;
}
i++;
}
// 使用指针输出乘法表
p_row = results;
i = 1;
while (i <= SIZE) {
p_col = *(p_row + i - 1);
int j = 1;
while (j <= SIZE) {
// 使用三元运算符控制输出格式
printf(j <= i ? "%d*%d=%-2d " : " ",
j, i, *(p_col + j - 1));
j++;
}
putchar('\n');
i++;
}
return 0;
}
再来一个:画出“*”组成的金字塔,需要注意以下几点:
- 使用全指针操作(不能直接使用数组下标访问)
- 使用三元运算符进行条件判断
- 使用while循环实现迭代控制
- 绘制表格线包围金字塔
#include <stdio.h>
#include <stdlib.h>
#define ROWS 9 // 金字塔层数
#define CELL_WIDTH 18 // 单元格宽度(考虑金字塔最底层的宽度)
// 打印水平分隔线
void printHorizontalLine() {
int i = 0;
while (i < CELL_WIDTH + 2) { // +2考虑左右边框
printf("-");
i++;
}
printf("\n");
}
int main() {
// 分配内存用于存储每行内容
char (*pyramid)[CELL_WIDTH + 1] = malloc(ROWS * sizeof(char[CELL_WIDTH + 1]));
if (!pyramid) {
printf("Memory allocation failed\n");
return 1;
}
// 使用指针填充金字塔内容
char (*p_row)[CELL_WIDTH + 1] = pyramid;
int row = 0;
while (row < ROWS) {
char *p_col = *p_row;
int col = 0;
while (col < CELL_WIDTH) {
// 使用三元运算符决定星号位置
// 金字塔中心对称,每行星号数量为2*row+1
*(p_col + col) = (col >= (CELL_WIDTH/2 - row)) &&
(col <= (CELL_WIDTH/2 + row)) ? '*' : ' ';
col++;
}
*(p_col + CELL_WIDTH) = '\0'; // 字符串结束符
p_row++;
row++;
}
// 打印带表格线的金字塔
printHorizontalLine();
p_row = pyramid;
row = 0;
while (row < ROWS) {
printf("|%s|\n", *p_row); // 使用指针访问每行内容
p_row++;
row++;
}
printHorizontalLine();
// 释放内存
free(pyramid);
return 0;
}