C语言:定义函数将r进制整数转换为s进制整数。r与s均在1到10之间
时间: 2024-05-16 19:17:32 浏览: 18
下面是将r进制整数转换为s进制整数的C语言代码:
```c
#include <stdio.h>
#include <string.h>
void convert(int num, int r, int s, char *result) {
char digits[] = "0123456789";
int quotient = num;
int i = 0;
// 将r进制整数转换为10进制整数
int decimal = 0;
int base = 1;
while (quotient != 0) {
int remainder = quotient % 10;
decimal += remainder * base;
base *= r;
quotient /= 10;
}
// 将10进制整数转换为s进制整数
quotient = decimal;
while (quotient != 0) {
int remainder = quotient % s;
result[i++] = digits[remainder];
quotient /= s;
}
result[i] = '\0';
// 翻转字符串
int len = strlen(result);
for (int j = 0; j < len / 2; j++) {
char temp = result[j];
result[j] = result[len - j - 1];
result[len - j - 1] = temp;
}
}
int main() {
int num, r, s;
char result[100];
printf("请输入要转换的数字:");
scanf("%d", &num);
printf("请输入原进制和目标进制:");
scanf("%d%d", &r, &s);
convert(num, r, s, result);
printf("%d进制的%d转换为%d进制后为:%s\n", r, num, s, result);
return 0;
}
```
在函数`convert`中,先将r进制整数转换为10进制整数,然后再将10进制整数转换为s进制整数。使用`digits`数组存储数字字符,通过取模运算得到每一位上的数字,将其转换为字符并存储到`result`字符串中。最后将`result`字符串翻转,得到最终的s进制整数。在`main`函数中,读入要转换的数字和原进制、目标进制,调用`convert`函数进行转换,并输出结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)