#37642:


q0908309831@gmail.com (浪人飄飄)

學校 : 不指定學校
編號 : 234983
來源 : [140.118.154.127]
最後登入時間 :
2023-11-15 14:44:05
f698. 後序運算式求值 -- 板橋高中教學題 | From: [140.118.74.187] | 發表日期 : 2023-09-23 15:25

#include <stdio.h>
#include <string.h>
 
char Num_list[1000] = { '\0' }, Oper_list[1000] = { '\0' };
int count = 0, count_list = 0,count_bit = 0,count_num = 0, len_str = 0, Num[1000] = {0};
 
void StrToNum() {
int a = 0, b = 0; //幫助迴圈
if (Oper_list[0] == '-') {
count_bit = count_bit - 2;
a = count_bit;
 
for (int i = 0; i < count_bit; i++) {
b = Oper_list[i + 1] - '0';
for (int j = 0; j < a; j++) {
b = b * 10;
}
a--;
Num[count_num] = Num[count_num] + b;
}
Num[count_num] = -(Num[count_num] + (Oper_list[count_bit + 1] - '0'));
}
else {
count_bit = count_bit - 1;
a = count_bit;
 
for (int i = 0; i < count_bit; i++) {
b = Oper_list[i] - '0';
for (int j = 0; j < a; j++) {
b = b * 10;
}
a--;
Num[count_num] = Num[count_num] + b;
}
Num[count_num] = Num[count_num] + (Oper_list[count_bit] - '0');
}
 
count_num++;
count_bit = 0;
}
 
void oper(char d) {
count_num--;
switch (d) {
case '+':
Num[count_num - 1] = Num[count_num - 1] + Num[count_num];
Num[count_num] = 0;
break;
case '-':
Num[count_num - 1] = Num[count_num - 1] - Num[count_num];
Num[count_num] = 0;
break;
case '*':
Num[count_num - 1] = Num[count_num - 1] * Num[count_num];
Num[count_num] = 0;
break;
case '/':
Num[count_num - 1] = Num[count_num - 1] / Num[count_num];
Num[count_num] = 0;
break;
default:
printf("程式有問題");
break;
}
 
}
 
 
 
int main() {
 
 
scanf("%[^\n]", Num_list);
len_str = strlen(Num_list); //取長度做for迴圈
 
for (int i = 0; i < len_str; i++) {
//判斷是否是運算子
if ((Num_list[i] == '+' || Num_list[i] == '-' || Num_list[i] == '*' || Num_list[i] == '/') && (Num_list[i + 1] == ' ')){
oper(Num_list[i]);
}
else if (Num_list[i] == ' ' && !(Num_list[i-1] == '+' || Num_list[i-1] == '-' || Num_list[i-1] == '*' || Num_list[i-1] == '/')){ //將字串丟整數陣列
StrToNum();
for (int i = 0; i < 1000; i++) {
Oper_list[i] = '\0';
}
}
else if (Num_list[i] == ' ' && (Num_list[i - 1] == '+' || Num_list[i - 1] == '-' || Num_list[i - 1] == '*' || Num_list[i - 1] == '/')) { //將字串丟整數陣列
continue;
}
else if (i == len_str - 1 ){
if (Num_list[i] == '+' || Num_list[i] == '-' || Num_list[i] == '*' || Num_list[i] == '/')
oper(Num_list[i]);
else {
count_list = strlen(Oper_list);//因為OPER陣列隨時在變動
Oper_list[count_list] = Num_list[i];
count_bit++;
StrToNum();
}
}
else{
count_list = strlen(Oper_list);//因為OPER陣列隨時在變動
Oper_list[count_list] = Num_list[i];
count_bit++;
}
}
 
printf("%d", Num[0]);
 
 
 
return 0;
}
 
看到沒人用c寫,想說來試試,除錯除了6個小時,人麻了,有更好的編寫方式,歡迎提出。
 
ZeroJudge Forum