小程式(十六)簡單四則運算

2021-06-17 23:42:51 字數 2936 閱讀 9618

問題描述:

輸入乙個只包含個位數字的簡單四則運算表示式字串,計算該表示式的值

注:3.1、表示式只含 +, -, *, / 四則運算符,不含括號

3.2、表示式數值只包含個位整數(0-9),且不會出現0作為除數的情況

3.3、要考慮加減乘除按通常四則運算規定的計算優先順序

3.4、除法用整數除法,即僅保留除法運算結果的整數部分。比如8/3=2。輸入表示式保證無0作為除數情況發生

3.5、輸入字串一定是符合題意合法的表示式,其中只包括數字字元和四則運算符字元,除此之外不含其它任何字元,不會出現計算溢位情況

要求實現函式:

int calculate(int len,char *expstr)

【輸入】 int len: 字串長度;char *expstr: 表示式字串;

【輸出】 無

【返回】 計算結果

示例:1)輸入:char *expstr = 「1+4*5-8/3」

函式返回:19

2)輸入:char *expstr = 「8/3*3」

函式返回:6

第一種方法:利用字尾表示式:

#include#include#includeusing namespace std;

int calculate(int len,char *expstr)

while(!oper.empty() && oper.top()!='(')

oper.push(expstr[i]);

break;

case'*':

case'/':if(oper.empty())

if(oper.top()!='*'&&oper.top()!='/')

oper.push(expstr[i]);

else

oper.push(expstr[i]);

}break;

case'(':oper.push(expstr[i]);break;//左括號在進棧前,認為優先順序是最大的

case')':while(oper.top()!='(')

oper.pop();

break;

default:exit(0);

}} while(!oper.empty())

postfix[j]='\0';

//printf("%s\n",postfix);

//利用字尾表示式求值

//每當遇到乙個操作符是,就將它的前兩個數彈出

//計算相應的值以後,再把結果入棧

int postfix_len = strlen(postfix);

stackpos_str;

int t1,t2,t;

for(i=0;i

第二種方法:利用棧和優先順序來算,不過這種方法中間計算的結果也不能大於10,並且不能加括號

#include#include#include#includeusing namespace std;

stackoptr;//運算子

stackopnd;//運算數

int in(char c)

}char precede(char t1,char t2) //t1是棧頂元素,t2是原表示式的字元

if(t1=='*' || t1=='/')

return '>';

}char operate(char a,char theta,char b)

//c = char(c);

return c;

}int calcucate(int len, char *expstr)

else if(c>='0' && c<='9')

else //c是非法字元

x = optr.top();

}x = opnd.top();

return x;

}int main()

第三種方法:用陣列模擬棧的實現,不帶括號

#include#include#includeint calculate(int len,char *expstr)

if(expstr[i]=='/')

} char oper_now;//計算只有加減的運算

int flag = datatop;

int data_num = 0,oper_num = 0;

while(data_num

以上都是運算元是個位數,如果運算元大於1位,那麼我們可以用以下方法來將多個字元轉化為數字:

int leftnum = converttodigit(pinputstr)

int converttodigit(const char *&str)//將從str開始的數字即其後的數字轉換為int,最終str指向下乙個運算子或'\0'.

int result = 0;

while (isdigit(*str))

return result;

}

運算元大於1位的四則運算的**:

#include#include#include#include#includeint covertodigit(char *s,int &num)

return m;

}int calculate(int len,char *expstr)

{ int *data = (int *)malloc(sizeof(int)*len);

char *oper = (char *)malloc(sizeof(char)*len);

int datatop = -1;

int opertop = -1;

int sum = 0;

int m = 0;

int num = 0;

for(int i=0;i

python四則運算程式 四則運算(Python)

四則運算程式 一 資訊 二.題目要求 寫乙個能自動生成小學四則運算題目的程式,然後在此基礎上擴充套件 除了整數以外,還要支援真分數的四則運算,例如 1 6 1 8 7 24 程式要求能處理使用者的輸入,判斷對錯,累積分數 程式支援可以由使用者自行選擇加 減 乘 除運算 三 import random...

簡單四則運算

form1 如下 using system using system.collections.generic using system.componentmodel using system.data using system.drawing using system.linq using syst...

簡單四則運算

實現乙個簡單的四則混合運算。並且在計算100範圍以內。我實現的是兩位數之間的加減乘除混合運算,首先先定義幾個量。然後思考一下你所想要的計算方式,我在這裡就簡單的進行了數字的加減乘除,進行分為各種情況,這裡僅僅把四組的數字的混合運算一下,然後新增監聽並達到的要求。我的這個四則運算存在很多的不足,例如乘...