所以我有这个循环来检查用户输入:
int ch, num;
while ((ch = getchar()) != '\n')
{
if (isdigit(ch))
{
num = ch - 48;
}
}
所以根据这个表:
Character Decimal Value
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
我使用这种方式获取我的号码
:num = ch - 48
;
例如,如果我想将我的 number
乘以 10
?
最佳答案
how to get normal value of int without using value - 48?
像这样:
num = ch - '0';
了解更多信息How to convert char to integer in C?
在这两种情况下,您只需执行以下操作:
num *= 10;
因为 num
的类型为 int
。
警告:其他人建议 int atoi (const char * str);
获取数字,它需要输入字符串,而不是字符!因此,如果您将一个字符传递给该函数(因此是一个非空终止字符串,您将调用未定义的行为)。
关于C编程: how to get normal value of int without using value - 48?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47468228/