#include <stdio.h>
#include <stdlib.h> /* for atof() */
#define MAXOP 100 /* max size of operand or operator */
#define NUMBER '0' /* signal that a number was found */
int getop(char []);
void push(double);
double pop(void);
/* reverse Polish calculator */
main()
{
int type;
double op2;
char s[MAXOP];
while ((type = getop(s)) != EOF) {
switch (type) {
case NUMBER:
push(atof(s));
break;
case ' ':
push(pop() pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '/':
op2 = pop();
if (op2 != 0.0)
push(pop() / op2);
else
printf("error: zero divisor\n");
break;
case '\n':
printf("\t%.8g\n", pop());
break;
default:
printf("error: unknown command %s\n", s);
break;
}
}
}
#define MAXVAL 100
int sp = 0;
double val[MAXVAL];
void push(double f)
{
if(sp < MAXVAL)
val[sp ]=f;
else
printf("error:stack full, cant push %g\n",f);
}
double pop(void)
{
if(sp>0)
return val[--sp];
else
{
printf("error: stack empty\n");
return 0.0;
}
}
#include<ctype.h>
int getch(void);
void ungetch(int);
int getop(char *s)
{
char c;
while ((*s = c = getch()) == ' ' || c == '\t')
;
*(s 1) = '\0';
if (!isdigit(c) && c != '.')
return c;
if (isdigit(c))
{
while (isdigit(*s = c = getch()))
;
}
if (c == '.')
{
while (isdigit(*s = c = getch()))
;
}
*s = '\0';
if (c != EOF)
ungetch(c);
return number;
}
char buf[30];
char *Bufp = buf;
int getch(void)
{
return (Bufp > buf) ? *(--Bufp) : getchar();
}
void ungetch(int c)
{
if (c != EOF)
*Bufp = c;
else
printf("no space\n”);
}
結果如下。 在此處輸入影像描述
當我更改此部分時。
int getch(void);
void ungetch(int);
int getop(char *s)
{
char c;
while ((*s = c = getch()) == ' ' || c == '\t')
;
*(s 1) = '\0';
if (!isdigit(c) && c != '.')
return c;
if (isdigit(c))
{
while (isdigit(* s = c = getch()))
;
}
if (c == '.')
{
while (isdigit(* s = c = getch()))
;
}
*s = '\0';
if (c != EOF)
ungetch(c);
return number;
}
結果是正確的。結果如下在此處輸入影像描述
所以我知道之間肯定有區別
while (isdigit(* s = c = getch()))
和
while (isdigit(* s = c = getch()))
這個問題必須與操作員的優先級有關。但我仍然不明白它發生的原因。你愿意幫助我嗎?或者你能告訴我類似的問題嗎?因為我找了很久??
———————————————————————上面的問題已經解決了。新的問題如下。
首先,感謝你們幫助我并為我提供了關于上述問題的新方向。但我仍然有疑問。為了
while (isdigit(* s = c = getch()))
我用更好理解的方式來達到同樣的效果
while (c = getch())
{
s;
if (isdigit(*s = c))
;
else
break;
}
同樣的方式
while (isdigit(* s = c = getch()))
更好理解的代碼
while (c = getch())
{
if (isdigit(*s = c))
{
s ;
}
else
break;
}
我不明白的* s = c是等于* (s ) = c。為什么陳述句與以下代碼不同?
s ;
*s = c;
運算子 的優先級高于*and =,對嗎?
uj5u.com熱心網友回復:
哦,我明白了。具有更高優先級的運算子并不一定意味著它首先發生。特別是對于后增量,直到變數具有有效值(或該值已被使用)才會發生。
所以,首先我們得到一個字符 getch(),然后將它分配給c變數。接下來,對于* s = c,盡管它等于 ,但在指標變數具有其有效值* (s ) = c之前不會發生增量。s執行陳述句*s = c。最后,如果*s是數字,請執行 s .
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/462809.html
上一篇:Go賦值涉及到自定義型別的指標
