gpt4 book ai didi

c - 这个从输入中读取数字的函数如何工作?

转载 作者:行者123 更新时间:2023-11-30 20:56:52 25 4
gpt4 key购买 nike

如何将字符串处理为整数以及按位运算符的用途。该函数已在 c 中用于从数字字符串中获取输入

    "gc and ll are defined like this.. typedef long long LL; 
#define gc getchar_unlocked()"

inline LL inp()
{
LL num = 0;
char p = gc;
while(p<33)p=gc;
while(p>33) {
num = (num << 3)+ (num << 1)+ (p -'0');
p = gc;
}
return num;
};

最佳答案

我推测char p = gcinput 获取一个字符.

while(p<33)p=gc;只是不断获取输入,直到输入空格以外的内容? (空格是十进制的第 32 个字符)。

然后,虽然输入不是空格,

(num << 3) + (num << 1)相当于 num * 10 ( num << 3 相当于 num * 8num << 1 相当于 num * 2num * 8 + num * 2 可以写成 num * (8+2) ,简化为 num * 10 )。

p - '0'将输入字符(例如“9”[char 57])转换为相应的整数(例如,仅 9)。

如果输入是“123”,那么 num 将等于 123,因为:

数字=0;

数字 = 0 * 10 + 1; (== 1)

数字 = 1 * 10 + 2; (== 12)

数字 = 12 * 10 + 3; (== 123)

我希望这能带来一些启发。这是非常糟糕的代码,如果输入数字 0-9 以外的任何内容,则不会正确运行。

这样写可能会更好:

// function to read one character from the 'input'
char gc();

// I'm not sure what LL is here, could be long long?
inline LL inp()
{
LL num = 0;
char p = gc();

// keep reading characters until a number is encountered
while((p < '0') || (p > '9'))
{
p = gc();
}

// loop until a non-number is encountered
while((p >= '0') && (p <= '9'))
{
// Shift the previously read digits up by one 'tens' column
num *= 10;

// Add in the newly read digit
num += p -'0';

// Read the next character
p = gc();
}

return num;
}

关于c - 这个从输入中读取数字的函数如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19076421/

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