麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 學院 > 開發設計 > 正文

c++學習筆記,一個簡單的計算器(控制臺)

2019-11-14 09:49:43
字體:
來源:轉載
供稿:網友

//--------------------------------------【程序說明】-------------------------------------------//開發測試所用操作系統Windows 7 32bit//開發測試所用IDE版本:Visual Studio 2015

// A PRogram to implement a calculator accepting parentheses    一個程序實現一個計算器接受括號

#include <iostream>                   // For stream input/output     輸入/輸出流#include <cstdlib>                    // For the exit() function    退出()函數#include <cctype>                     // For the isdigit() function     isdigit()函數#include <cstring>                    // For the strcpy() function      strcpy()函數using std::cin;using std::cout;using std::cerr;using std::endl;void eatspaces(char* str);            // Function to eliminate blanks          函數來消除空格double expr(char* str);               // Function evaluating an expression     函數計算一個表達式double term(char* str, int& index);   // Function analyzing a term             函數分析一個詞double number(char* str, int& index); // Function to recognize a number        函數來識別一個數字char* extract(char* str, int& index); // Function to extract a substring       函數來提取子字符串const int MAX(80);                    // Maximum expression length,            最大表達長度 // including '/0'                         包括' / 0int main(){char buffer[MAX] = { 0 };    // Input area for expression to be evaluated   輸入表達式計算cout << endl<< "Welcome to your friendly calculator."<< endl<< "Enter an expression, or an empty line to quit."<< endl;for (;;){cin.getline(buffer, sizeof buffer);   // Read an input line                  讀取一個輸入行eatspaces(buffer);                    // Remove blanks from input            從輸入刪除空格if (!buffer[0])                        // Empty line ends calculator         空行結束計算器return 0;try{cout << "/t= " << expr(buffer)      // Output value of expression        輸出值的表達式<< endl << endl;}catch (const char* pEx){cerr << pEx << endl;cerr << "Ending program." << endl;return 1;}}}// Function to eliminate spaces from a string          從一個字符串函數來消除空間void eatspaces(char* str){int i(0);                              // 'Copy to' index to string            “復制到”索引的字符串int j(0);                              // 'Copy from' index to string           “臨摹”索引的字符串while ((*(str + i) = *(str + j++)) != '/0')  // Loop while character            循環而性格// copied is not /0                 復制不/ 0if (*(str + i) != ' ')                    // Increment i as long as          只要增量i++;                                  // character is not a space       不是一個空間return;}// Function to evaluate an arithmetic expression                                    函數來評估一個算術表達式double expr(char* str){double value(0.0);                   // Store result here                              這里存儲結果int index(0);                        // Keeps track of current character position      跟蹤當前的字符位置value = term(str, index);            // Get first term                                 得到第一個任期 for (;;)                              // Indefinite loop, all exits inside             無限循環,所有出口{switch (*(str + index++))           // Choose action based on current character    基于當前的角色選擇行動{case '/0':                       // We're at the end of the string                 我們在結束的字符串return value;                 // so return what we have got                    所以我們必須返回case '+':                        // + found so add in the                          +發現添加的value += term(str, index);    // next termbreak; case '-':                        // - found so subtract                            ——發現減去value -= term(str, index);    // the next termbreak;default:                         // If we reach here the string                    如果我們到達這里的字符串char message[38] = "Expression evaluation error. Found: ";           //表達式求值的錯誤。發現:strncat_s(message, str + index - 1, 1);  // Append the character                添加角色throw message;break;}}}// Function to get the value of a term                            功能詞的價值double term(char* str, int& index){double value(0.0);                   // Somewhere to accumulate                        積累的地方    // the result                                      value = number(str, index);          // Get the first number in the term              得到第一個數字// Loop as long as we have a good Operator        循環,只要我們有一個優秀的經營者while (true){if (*(str + index) == '*')          // If it's multiply,                           如果是用,value *= number(str, ++index);   // multiply by next number                     乘下一個數字else if (*(str + index) == '/')     // If it's divide,                             如果它是分裂, value /= number(str, ++index);   // divide by next number                      除以下一個數字elsebreak;}return value;                        // We've finished, so return what                  我們已經完成了,所以返回什么// we've got                                       我們有}// Function to recognize a number in a string                                             函數來識別一個數字字符串double number(char* str, int& index){double value(0.0);                   // Store the resulting value                   將得到的值存儲到if (*(str + index) == '(')            // Start of parentheses                       括號開始{char* psubstr(nullptr);            // Pointer for substring                     子串的指針psubstr = extract(str, ++index);   // Extract substring in brackets              提取子字符串在括號中value = expr(psubstr);             // Get the value of the substring             子字符串的值delete[]psubstr;                   // Clean up the free store                    清理免費存儲return value;                      // Return substring value                     返回字符串值}// There must be at least one digit...if (!isdigit(*(str + index))){ // There's no digits so input is junk...           沒有數字的輸入是垃圾……char message[31] = "Invalid character in number: ";      //無效的字符的數量:strncat_s(message, str + index, 1);  // Append the characterthrow message;}while (isdigit(*(str + index)))       // Loop accumulating leading digits          循環累積領先的數字value = 10 * value + (*(str + index++) - '0');// Not a digit when we get to hereif (*(str + index) != '.')            // so check for decimal point                 所以檢查小數點return value;                      // and if not, return value                  如果沒有,返回值double factor(1.0);                  // Factor for decimal places                    小數點后因素while (isdigit(*(str + (++index))))   // Loop as long as we have digits            循環只要我們有數字{factor *= 0.1;                     // Decrease factor by factor of 10            減少因素的10倍value = value + (*(str + index) - '0')*factor;   // Add decimal place            增加小數位}return value;                        // On loop exit we are done                     在循環退出做完了}// Function to extract a substring between parentheses           括號之間的函數來提取子字符串// (requires cstring)char* extract(char* str, int& index){char* pstr(nullptr);                // Pointer to new string for return              指針指向新的字符串返回int numL(0);                        // Count of left parentheses found                 計算左括號的發現int bufindex(index);                // Save starting value for index                保存起始值指數do{switch (*(str + index)){case ')':if (0 == numL){++index;pstr = new char[index - bufindex];if (!pstr){throw "Memory allocation failed.";}strncpy_s(pstr, index - bufindex, str + bufindex, index - bufindex - 1); // Copy substring to new memory   子串復制到新的記憶return pstr;                                                     // Return substring in new memory            返回字符串在新的記憶}elsenumL--;                                                          // Reduce count of '(' to be matched        減少“(”匹配的計數break;case '(':numL++;                                                            // Increase count of '(' to be                  增加的“(”  // matchedbreak;}} while (*(str + index++) != '/0');                                       // Loop - don't overrun end of string            循環——不要泛濫字符串的結束throw "Ran off the end of the expression, must be bad input.";}

成功圖片如下:


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 亚洲第一页中文字幕 | 密室逃脱第一季免费观看完整在线 | 午夜精品久久久久久久99热浪潮 | 在线播放免费播放av片 | 精品一区二区三区免费爱 | 亚洲欧美国产高清 | hd日本xxxx| 日本在线看 | 国产欧美精品一区二区三区四区 | 午夜精品区| 综合国产一区 | 久久亚洲春色中文字幕久久 | 久久精品高清 | 久久久久九九九女人毛片 | 日韩视频一区 | 国产精品91久久久 | 一级做受毛片免费大片 | 中文字幕在线资源 | 91成| 欧美日韩在线播放 | 黄色片免费看网站 | 免费观看国产视频 | 国产1区2 | 毛片在线免费观看网址 | 欧美精品在线视频观看 | 国产精品视频专区 | 成人店女老板视频在线看 | 国产一区二区三区在线免费 | 99国内精品 | 99影视在线视频免费观看 | 91成人免费在线观看 | 蜜桃视频在线免费观看 | 久久久久久久久成人 | 日韩精品二区 | 欧美大荫蒂xxx | 黄视频免费在线 | 亚洲成人黄色片 | 欧美一级毛片大片免费播放 | 黄色二区三区 | 久久亚洲春色中文字幕久久 | 91成人在线网站 |