簡易計算器編寫

2021-10-19 10:56:27 字數 2780 閱讀 8955

寫了乙個計算器, 控制台版的,只做加減乘除法, 無視多餘空格。

考慮寫乙個qt版本圖形介面版的,給加上小數運算和支援各類三角函式

重要思想如下:

#define _crt_secure_no_warnings

#include #include #include #include #include using namespace std;

mapprecedence;

bool isoperator(char ch)

bool isoperand(char c)

void initpriority()

void topostfix(const char* pszbuf, char *pszret)

nsize = strlen(pszbuf);

for (size_t nidx = 0; nidx < nsize; ++nidx)

// 運算元直接進入結果佇列

if (true == isoperand(ch))

}else

// 遇到右括號開始彈棧並把內容壓入結果佇列直到碰到左括號

else if (')' == ch)

pszret[idx++] = ctmp;

pszret[idx++] = ' ';}}

// 遇到加減乘除按照優先順序,如果遇到符號棧內

// 碰到了優先順序更高的符號

else

else

op.push(ch);}}

} }while (!op.empty())

cout << "字尾表示式: " << pszret << endl;

}void trimmedspace(char *pszstr)

// 指向當前字串

pszcurpos = pszstr;

nsize = strlen(pszstr);

// 分配與原字串相同大小的空間

psznewbuf = new char[nsize + 1];

memset(psznewbuf, 0, nsize + 1);

// 除空格,tab和換行符外全部複製到新空間內

for (size_t nidx = 0; *pszcurpos; ++pszcurpos) }

strcpy(pszstr, psznewbuf);

// 釋放新空間

if (nullptr != psznewbuf) }

char *addinterval(char *pszbuf)

// 確定空間大小

nsize = strlen(pszbuf);

nnewbufsize = 2 * nsize;

// 分配新空間

pnewbuf = new char[nnewbufsize];

memset(pnewbuf, 0, nnewbufsize);

for (size_t nidx = 0, nnewsize = 0; nidx < nsize; ++nidx) }

return(pnewbuf);

}void calc(char* pszexpress)

; size_t nsize = 0, nidx = 0;

char ch, cpre = 0;

stackoperandstack;

int ione = 0, itwo = 0, iresult = 0, idx = 0;

char* pszformatedexpress = nullptr;

char* ppostfix = nullptr;

if (nullptr == pszexpress)

// 首先清除掉所有空格

trimmedspace(pszexpress);

// 新增分隔符

pszformatedexpress = addinterval(pszexpress);

nsize = strlen(pszformatedexpress);

// 轉成字尾表示式

ppostfix = new char[nsize + 1];

memset(ppostfix, 0, nsize + 1);

topostfix(pszexpress, ppostfix);

if (nullptr == pszformatedexpress)

nsize = strlen(ppostfix);

for (size_t nidx = 0; nidx < nsize; ++nidx)

operandstack.push(iresult);

} // 判定是否是運算元, 並把運算元組合壓棧

else if (true == isoperand(ch) || ((' ' == ch) && (true == isoperand(cpre))))

else

cpre = ch;

} else

}if (!operandstack.empty())

delete ppostfix;

}int main()

; calc(pbuf);

while (true)

system("pause");

return(0);

}

結果顯示如下:

enjoy❥(^_-)

(完)

用C 編寫簡易貸款計算器

今年大二開設的課程是c 程式設計,才開始學習c 這個物件導向的語言。感覺有些地方和c語言差不多,但是還是稍微有點不習慣。下面是我自己寫的 using system using system.collections.generic using system.linq using system.text...

簡易計算器

include include include char xpr expression int level char ch double calc int lim return ret int main cal的遞迴使用,利用了當 運算子運算完畢以後,仍然會留在這個位置 比如式子 3 5 2 的分析...

簡易計算器

cpp copyright c 2012,煙台大學計算機學院 all rights reserved.檔名稱 text.cpp 作 者 胡穎 完成日期 2013 年 6 月 28 日 版 本 號 v1.0 輸入描述 輸入操作指令及計算的數字 符號 問題描述 製作簡易計算器 程式輸出 輸出操作頁面及計...