每日一记:画图

思考:我们可以在控制台输出数值,也能进行计算或者打印我们想要的一句话,那么这位“朋友”有没有别的本领?嘿嘿:自然是有介绍这位朋友的另一个本事——画图

上才艺!先说好:这里我用的while循环

如果你有更好的见解,欢迎在评论区留言,讨论!

先来画个9*9乘法表,需要注意一下几点

  1. 双重循环结构(外层控制行,内层控制列)
  2. 格式化输出对齐
  3. 指针遍历代替数组下标访问
  4. 使用三元运算符处理特殊情况
#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;
}

再来一个:画出“*”组成的金字塔,需要注意以下几点:

  1. 使用全指针操作(不能直接使用数组下标访问)
  2. 使用三元运算符进行条件判断
  3. 使用while循环实现迭代控制
  4. 绘制表格线包围金字塔
#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

司铭鸿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值