C++ - A Simple Calculator Program

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

/***************************************************** A program to implement a calculator - By Chimomo****************************************************/#include <iostream>                                              // For stream input/output#include <cstdlib>                                               // For the exit() function#include <cctype>                                                // For the isdigit() function#include <cstring>using std::cin;using std::cout;using std::endl;void eatspaces(char* str);                                       // Function to eliminate blanksdouble expr(char* str);                                          // Function evaluating an expressiondouble term(char* str, int& index);                              // Function analyzing a termdouble number(char* str, int& index);                            // Function to recognize a numberchar* extract(char* str, int& index);                            // Function to extract a substringconst int MAX(80);                                               // Maximum expression length, including '\0'int 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." << endlfor(;;) {  cin.getline(buffer, sizeof buffer);                      // Read an input line  eatspaces(buffer);                                       // Remove blanks from input  if(!buffer[0])                                           // Empty line ends calculator   return 0;  cout << "\t= " << expr(buffer) << endl << endl;          // Output value of expression }}// Function to eliminate spaces from a stringvoid 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 is not \0  if(*(str + i) != ' ')                                    // Increment i as long as character is not a space   i++; return;}// Function to evaluate an arithmetic expressiondouble expr(char* str)double value(0.0);                                           // Store result here int index(0);                                                // Keep track of current character position value = term(str, index);                                    // Get first term for(;;)                                                      // Indefinite loop, all exists inside {  switch(*(str + index++))                                 // Choose action based on current character  {  case '\0':                                               // We are at the end of the string   return value;                                        // So return what we have got  case '+':                                                // + found so add in the next term   value += term(str, index);   break;  case '-':                                                // - found so subtract the next term   value -= term(str, index);   break;  default:                                                 // If we reach here the string is junk   cout << endl << "Arrrgh!*#!! There's an error" << endl;   exit(1);  } }}// Function to get the value of a termdouble 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, multiply by next number   value *= number(str, ++index);  else if(*(str + index) == '/')                           // If it's divide, divide by next number   value /= number(str, ++index);  else   break; } return value;                                                // We've finished, so return what we've got}// Function to recognize an expression in parentheses or a number in a stringdouble 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...  cout << endl << "Arrgh!*#!! There's an error" << endl;  exit(1); } while(isdigit(*(str+index)))                                 // Loop accumulating leading digits  value = 10*value + (*(str+index++)-'0'); if(*(str+index) != '.')                                      // Not a digit when we get to here 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  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> header file)char* extract(char* str, int& index)char buffer[MAX];                                            // Temporary space for substring 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 {  buffer[index - bufindex] = *(str + index);  switch(buffer[index - bufindex])  {  case ')':   if(0 == numL)   {    buffer[index - bufindex] = '\0';                 // Replace ')' with '\0'    ++index;    pstr = new char[index - bufindex];    if(!pstr)    {     cout << "Memory allocation failed," << " program terminated.";     exit(1);    }    strcpy_s(pstr, index-bufindex, buffer);          // Copy substring to new memory    return pstr;                                     // Return substring in new memory   }   else    numL--;                                          // Reduce count of '(' to be matched   break;  case '(':   numL++;                                              // Increase count of '(' to be matched   break;  } }while(*(str + index++) != '\0');                            // Loop - don't overrun end of string cout << "Ran off the end of the expression, must be bad input." << endlexit(1);}// Output:/*Welcome to your friendly calculator.Enter an expression, or an empty line to quit.3*7        = 21Press any key to continue . . .*/
           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow
这里写图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值