アルゴリズム ( )
本問を選択(Select this problem){ する(Yes),しない(No) } No.
次のプログラムは数式を計算する。The following program calculates a mathematical expression.
#include<stdio.h>
int e();
int f();
char token;
int e() { int a = f();
while (token == ’+’) { token = getchar();
a += f();
}
return a;
}
int f() { int a;
if (token == ’(’) { token = getchar();
a = e();
if (token ==’)’) { token = getchar();
return a;
} else
return 0;
}
else if ((’0’ <= token) && (token <= ’9’)) { a = token - ’0’;
token = getchar();
return a;
} else {
token = getchar();
return 0;
} }
int main() {
token = getchar();
printf("%d\n", e());
return 0;
}
(1) 次の入力に対する出力を書け。Write the output of the above program for the following input:
(1-a) 1+2+(3+4)+5 (1-b) 1++2++3 (1-c) 1+a+2 (1-d) 1+(2+3a+4
(2) 掛け算 (*) も扱いたい。どう直せばよいか説明せよ。We wish to allow multiplication (*). Explain how to modify.
(3) 単項演算 +と -を追加したい。どう直せばよいか。We wish to add unary operations +and -. Explain how to modify.
(解答は裏面を使用しても構わない.You can use the reverse side of this answer sheet for your answering.)