所以我希望在这方面得到一些指导。我有一个接受基数(基数)的函数,然后使用 getchar() 将获取要从给定基数转换为整数表示的数字。
给出的唯一参数是基数,然后 getchar() 通过命令行获取数字表示。
如果我通过了
str2int 16
input a number: 3c
它应该输出 (16^1*3) + (16^0*12) = 48 + 12 = 60。
我完全理解数学和转换碱基的不同方法,但不知道如何编写代码。数学总是比代码简单得多,至少对我而言。
另一种计算方法是: (702) 基数 15 = 15*7 + 0 = 105; 15*105 + 2 = 1577
我不知道如何仅使用 getchar() 在 C 中表达它?可以不使用数学函数吗?
最佳答案
一直一次获取一个char
,直到不需要一个数字或不再需要为止。
unsigned shparkison(unsigned base) {
unsigned sum = 0;
int ch;
while ((ch = getchar()) != EOF) {
// one could instead look up the toupper(value) in an array "0123...ABC...Z";
// Following assumes ASCII
if (isdigit(ch)) ch -= '0';
else if (islower(ch)) ch -= 'A' - 10;
else if (isupper(ch)) ch -= 'a' - 10;
else {
break; // Not a digit
}
if (ch >= base) {
break; // Digit too high
}
unsigned sum_old = sum;
sum *= base;
sum += ch;
if (sum < sum_old) {
sum = sum_old;
break; // Overflow
}
}
ungetc(ch, stdin);
return sum;
}
关于将数字从 n 基数转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18839099/