gpt4 book ai didi

当前 = 当前 * 10 + (c - '0' );

转载 作者:太空狗 更新时间:2023-10-29 15:45:52 30 4
gpt4 key购买 nike

我试图通过这段代码读取未知数量的整数:

while (1) {
int c = getchar ();
if (c == EOF)
break;
else if (isdigit (c))
current = current * 10 + (c - '0');
else {
total += current;
current = 0;
}
}

我知道什么 current = current * 10 + (c - '0');会,但我不知道为什么会有 c - '0'。你能给我解释一下吗?提前谢谢你。

最佳答案

c - '0' 是将单个 ASCII 数字转换为整数的基本方法。

例如,如果c等于'9',那么它的整数值为0x39'0' 的 ASCII 值为 0x30,因此,0x39-0x30 == 0x09 等于整数值 9

这是数字的 ASCII 表:

chr  hex   dec
'0' 0x30 48
'1' 0x31 49
'2' 0x32 50
'3' 0x33 51
'4' 0x34 52
'5' 0x35 53
'6' 0x36 54
'7' 0x37 55
'8' 0x38 56
'9' 0x39 57

关于当前 = 当前 * 10 + (c - '0' );,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22229107/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com