将一个十进制数转化成n进制输出,用C语言编写
时间: 2023-06-13 07:03:40 浏览: 72
以下是将十进制数转化为n进制的C语言代码:
```c
#include <stdio.h>
void decimal_to_n(int num, int base) {
if (num == 0) {
return;
}
int remainder = num % base;
decimal_to_n(num / base, base);
if (remainder < 10) {
printf("%d", remainder);
} else {
printf("%c", remainder - 10 + 'A');
}
}
int main() {
int num, base;
printf("Enter the decimal number: ");
scanf("%d", &num);
printf("Enter the base: ");
scanf("%d", &base);
printf("The number %d in base %d is: ", num, base);
decimal_to_n(num, base);
printf("\n");
return 0;
}
```
首先,我们定义了一个名为`decimal_to_n`的函数,它接受两个参数:要转换的十进制数和目标进制。这个函数使用递归来将数字转换为目标进制,并在递归结束时依次输出每个数字。
然后,在`main`函数中,我们要求用户输入要转换的十进制数和目标进制,并使用`decimal_to_n`函数将数字转换为目标进制。最后,我们输出结果。
值得注意的是,当余数大于等于10时,我们使用`printf("%c", remainder - 10 + 'A')`的方式输出字母。这是因为在十六进制及以上的进制中,我们需要使用字母来表示数字,其中A表示10,B表示11,以此类推。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)