c-moodle/homework/11989.c

63 lines
2.1 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
// 函数名称DigiTran
// 函数功能将整数k变换为一个字母串
// 参数int k要转换的整数char res[](存储转换结果的字符数组)
void DigiTran(int k, char res[]);
int s;
int main() {
while (scanf("%d", &s)) { // 循环读入整数
if (s == -1) { // 如果读入数字为-1则退出循环
return 0;
}
char res[233]; // 存储结果的字符数组
DigiTran(s, res); // 调用DigiTran函数进行转换
printf("%s ", res); // 输出转换结果
}
}
// 函数名称ws
// 函数功能:获取一个整数的位数
// 参数int a要获取位数的整数
int ws(int a) {
int ans = 0;
while (a) { // 当a不为0时继续循环
ans++;
a /= 10; // 每次除以10向下取整
}
return ans; // 返回位数
}
void DigiTran(int k, char res[]) {
int rr[233];
if (k == 0) { // 如果k为0直接将res赋值为A
res[0] = 'A';
res[1] = '\0'; // 字符串结尾
return; // 直接返回
}
int n = ws(k); // 获取k的位数
for (int i = 0; i < n; i++) {
rr[n - i - 1] = k % 10; // 将k的每一位存入数组rr中
k /= 10;
}
// rr 为将数组拆解为一位一位的数组
int ki = 0; // 标识res的位数
for (int i = 0; i < n; i++) {
if (i == n - 1) { // 如果已经到达最后一位
res[ki++] = rr[i] + 'A'; // 将当前位转换为字母后存入res中
continue; // 直接进行下一轮循环
}
int ls = rr[i] * 10 + rr[i + 1]; // 计算当前位和下一位组成的数字
// 如果两位数字合条件
if (ls >= 10 && ls <= 25) {
res[ki++] = ls + 'A'; // 将两位数字转换为字母后存入res中
i++; // 因为处理了两个数字所以i需要加1
} else { // 如果不符合条件,只用一个数字进行转换
res[ki++] = rr[i] + 'A'; // 将当前位转换为字母后存入res中
}
}
res[ki] = '\0'; // 添加字符串结尾
}