Online Compiler C

#include <stdio.h> void decimal_to_ternary(int n, char *result) { int i = 0; if (n == 0) { result[i++] = '0'; } else { int temp[32]; int len = 0; while (n > 0) { temp[len++] = n % 3; n /= 3; } for (int j = len - 1; j >= 0; j--) { result[i++] = temp[j] + '0'; } } result[i] = '\0'; } int main() { int n; scanf("%d", &n); char ternary[32]; decimal_to_ternary(n, ternary); printf("%s\n", ternary); return 0; }
1) 这段代码实现了一个将十进制整数转换为三进制字符串的功能。主函数读取用户输入的十进制数,调用decimal_to_ternary函数进行转换,最后输出结果字符串。

2) 提示:
- 注意理解temp数组的作用,它按逆序存储了三进制数的每一位
- 思考为什么最后需要从后往前遍历temp数组来构建结果字符串