【C 语言经典100例 | 菜鸟教程】C 语言练习实例8

解题思路

数字版的太没意思了。改成“使用C语言打印中文九九乘法表”。

L8.h

//
// Created by crazy_pig on 2022/8/31.
// References from : https://www.runoob.com/cprogramming/c-100-examples.html
//

#ifndef CTEST100_L8_H
#define CTEST100_L8_H

#endif //CTEST100_L8_H

#include 
#include 

#define CHN_CHAR_LEN 4
#define RESULT_CHAR_LEN 10

void getChnDesc(char *chn_num_char, int num);

void getSingleCnChar(char *chnNum, const char charArray[][CHN_CHAR_LEN], int index);

void copyArray(char *dstArray, const char *srcArray, int dst_offset);

/**
 * 题目:输出9*9口诀。
 * 程序分析:分行与列考虑,共 9 行 9 列,i 控制行,j 控制列。
 */
void L8();

L8.c

//
// Created by crazy_pig on 2022/8/31.
// References from : https://www.runoob.com/cprogramming/c-100-examples.html
//

#include 
#include "../include/L8.h"

/**
 * 题目:输出9*9口诀。
 * 程序分析:分行与列考虑,共 9 行 9 列,i 控制行,j 控制列。
 */
void L8() {
    int row, column, product;
    char *clnChar = (char *) malloc(CHN_CHAR_LEN);
    char *rowChar = (char *) malloc(CHN_CHAR_LEN);
    char *productChar = (char *) malloc(RESULT_CHAR_LEN);

    // 行:1-9
    for (row = 1; row <= 9; row++) {
        // 列:1-行数
        for (column = 1; column <= row; column++) {
            product = row * column;
            getChnDesc(clnChar, column);
            getChnDesc(rowChar, row);
            getChnDesc(productChar, product);

            printf("%s%s%s%s\t",
                   clnChar,
                   rowChar,
                   product >= 10 ? "" : "得",
                   productChar);

        }
        printf("\n");
    }
}

/**
 * 取得数字对应的中文
 * @param num 数字
 * @return 数字中文
 */
void getChnDesc(char *chn_num_char, int num) {
    char num_char_array[10][4] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    char unit_ten[1][4] = {"拾"};
    int last = 0, head = 0;
    if (num >= 10) {
        last = num % 10;
        head = num / 10;
    } else {
        last = num;
    }
    if (head != 0) {
        // 拼接十位和个位
        char *ten = (char *) malloc(CHN_CHAR_LEN);
        char *one = (char *) malloc(CHN_CHAR_LEN);
        getSingleCnChar(ten, num_char_array, head);
        copyArray(chn_num_char, ten, 0);
        copyArray(chn_num_char, unit_ten[0], 3);

        if (last > 0) {
            getSingleCnChar(one, num_char_array, last);
            copyArray(chn_num_char, one, 6);
            chn_num_char[9] = '\0';
        } else {
            // 中文发音习惯,零在最后不读
            chn_num_char[6] = '\0';
        }
    } else {
        // 直接返回
        getSingleCnChar(chn_num_char, num_char_array, last);
    }
}

void copyArray(char *dstArray, const char *srcArray, int dst_offset) {
    for (int i = 0; i < CHN_CHAR_LEN; ++i) {
        dstArray[i + dst_offset] = srcArray[i];
    }
}

void getSingleCnChar(char *chnNum, const char charArray[][CHN_CHAR_LEN], int index) {
    for (int i = 0; i < CHN_CHAR_LEN; ++i) {
        chnNum[i] = charArray[index][i];
    }
}

Result

【C 语言经典100例 | 菜鸟教程】C 语言练习实例8_第1张图片

你可能感兴趣的:(C语言,c语言,c++,算法)