⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 equation3-1.cpp

📁 This is solution code c++ in class lesson.
💻 CPP
字号:
#include<iostream>
using namespace std;
int main()
{
    string s;
    cout << "Enter a simple equation: ";
    getline(cin, s);
// extract operator and operands
// find the operator and position of operator
    char op = -1;
    int pos = '?';
    int plus = s.find("+",0);
    int minus = s.find("-",0);
    int multiply = s.find("*",0);
    int div = s.find("/",0);
    
    if (plus >= 0){
       pos = plus;
       op = '+';
    }else if(minus >= 0){
       pos = minus;
       op = '-';
    }else if(multiply >= 0){
       pos = multiply;
       op = '*';
    }else if(div >= 0){
       pos = div;
       op = '/';
    }else{
       cout << "not found any operator in the equation"<<endl;
       system("pause");
       return 0;
    }

// seperate operands
    string opd1 = s.substr(0,pos);    
    string opd2 = s.substr(pos+1,s.length()-pos);
    
// convert operand from string to integer
    // opd1
    int value1 = 0;
    int len = opd1.length();
    if (len == 3){
       value1 = ((int)(opd1.at(0) - '0')) * 100 +
                ((int)(opd1.at(1) - '0')) * 10 +
                (int)(opd1.at(2) - '0');
    }else if(len == 2){
       value1 = ((int)(opd1.at(0) - '0')) * 10 +
                (int)(opd1.at(1) - '0');   
    }else if(len == 1){
       value1 = (int)(opd1.at(0) - '0');
    }else{
       cout << "invalid size of operand" << endl;
       system("pause");
       return 0;
    }
    // opd2
    int value2 = 0;
    len = opd2.length();
    if (len == 3){
       value2 = ((int)(opd2.at(0) - '0')) * 100 +
                ((int)(opd2.at(1) - '0')) * 10 +
                (int)(opd2.at(2) - '0');
    }else if(len == 2){
       value2 = ((int)(opd2.at(0) - '0')) * 10 +
                (int)(opd2.at(1) - '0');   
    }else if(len == 1){
       value2 = (int)(opd2.at(0) - '0');
    }else{
       cout << "invalid size of operand" << endl;
       system("pause");
       return 0;
    }
// evaluate the operator and perform equation
    int result = 0;
    switch(op){
       case '+': result = value1 + value2;
                 break;
       case '-': result = value1 - value2;
                 break;
       case '*': result = value1 * value2;
                 break;
       case '/': result = value1 / value2;
                 break;
    }
    cout << s << " = " << result << endl;
    system("pause");
    return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -