所以我了解 getop 函数是什么以及它是如何工作的,但无法理解检查输入的整数和小数部分并将它们放入 s 数组中的 while 循环。
所以我一直在尝试以标准方式编写这些相同的 while 循环(括号中的表达式,然后括号中的下面的语句)。
所以而不是 while 循环是:
while(isdigit(s[++i] = c = getch())){
;
}
为什么不能:
while(isdigit(c = getch())){
s[++i] = c;
}
完整的 getop 函数:
int getop(char s[]){
int i, c;
while((s[0] = c = getch()) == ' ' || c == '\t'){
; //set s[0] to the first non space/tab char
}
s[1] = '\0'; //s[1] to \0
if(isdigit(c) == 0 && c != '.' && c != '-'){
return c; //if not a digit or . then return(must be a +,-,/,*)
}
i = 0;
if(isdigit(c)){
while(isdigit(s[++i] = c = getch())){
; //integer part
}
}
if(c == '.'){
while(isdigit(s[++i] = c = getch())){
; //fraction part
}
}
s[i] = '\0';
if(c != EOF){
ungetch(c);
}
return NUMBER;
}
但是输出并不相同,当使用替代 while 循环时,由于某种原因,最后一个输入被剪掉。因此输入 123 将返回 12。
最佳答案
while(isdigit(c = getch())){
s[++i] = c;
}
原始总是递增i
并分配给s[++i]
。如果 isdigit()
检查失败,您的版本将跳过这两个步骤。为了匹配原始行为,您需要在循环结束后执行一项额外的赋值和增量。
while(isdigit(c = getch())){
s[++i] = c;
}
s[++i] = c;
关于c - 无法理解 getop 函数中的最后两个 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58123470/