10503
题目
实现进制转换器:
(1) 输入一个十进制正整数
(2) 输入一个正整数
答案
c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
void decimalToBase() {
long long n;
int b;
char result[64];
int index = 0;
const char digits[] = "0123456789ABCDEF";
printf("请输入一个十进制正整数 N: ");
scanf("%lld", &n);
printf("请输入目标进制 b (2-16): ");
scanf("%d", &b);
if (b < 2 || b > 16) {
printf("错误: 进制 b 必须在 2 到 16 之间。\n");
return;
}
if (n < 0) {
printf("错误: 十进制数必须为正整数。\n");
return;
}
if (n == 0) {
printf("十进制数 0 在 %d 进制下为: 0\n", b);
return;
}
while (n > 0) {
result[index] = digits[n % b];
n /= b;
index++;
}
printf("转换结果为: ");
for (int i = index - 1; i >= 0; i--) {
printf("%c", result[i]);
}
printf("\n");
}
void baseToDecimal() {
char n_str[64];
int b;
long long decimalValue = 0;
int digitValue;
int len;
printf("请输入源进制 b (2-16): ");
scanf("%d", &b);
if (b < 2 || b > 16) {
printf("错误: 进制 b 必须在 2 到 16 之间。\n");
return;
}
printf("请输入一个 %d 进制的正整数 N: ", b);
scanf("%s", n_str);
len = strlen(n_str);
for (int i = 0; i < len; i++) {
char currentChar = toupper(n_str[i]);
if (currentChar >= '0' && currentChar <= '9') {
digitValue = currentChar - '0';
} else if (currentChar >= 'A' && currentChar <= 'F') {
digitValue = currentChar - 'A' + 10;
} else {
printf("错误: 输入的数 '%s' 包含非法字符 '%c'。\n", n_str, n_str[i]);
return;
}
if (digitValue >= b) {
printf("错误: 输入的数 '%s' 不是一个合法的 %d 进制数 (字符 '%c' 无效)。\n", n_str, b, n_str[i]);
return;
}
decimalValue = decimalValue * b + digitValue;
}
printf("%d 进制数 %s 在十进制下为: %lld\n", b, n_str, decimalValue);
}
int main() {
int choice;
while (1) {
printf("\n--- 进制转换器 ---\n");
printf("1. 十进制 -> b 进制\n");
printf("2. b 进制 -> 十进制\n");
printf("3. 退出\n");
printf("请选择功能: ");
if (scanf("%d", &choice) != 1) {
printf("无效输入,请输入数字。\n");
while (getchar() != '\n');
continue;
}
switch (choice) {
case 1:
decimalToBase();
break;
case 2:
baseToDecimal();
break;
case 3:
printf("程序已退出。\n");
return 0;
default:
printf("无效选择,请输入 1, 2, 或 3。\n");
}
}
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121