C++计算器和 for 循环

C++ calculator and for loop

本文关键字:循环 for 计算器 C++      更新时间:2023-10-16
string Expression::addevaluate(string x){
    stringrep = x;   //Stringrep is the string that user typed in, 
                     //it might be 5+6+7-8-9*3/(2+5)
    int totalnum = stringrep.length();
    for(int i=0;i < totalnum;i++){    //This for loop will seperate the 
                                      //string by "+" and output a vector 
                                      //with seperate string
        int addop = stringrep.find("+");
        addvector.push_back(stringrep.substr(0,addop));
        string a =stringrep.substr(0,addop);
        totalnum=totalnum-(a.length());
        stringrep = stringrep.substr(addop+1,totalnum);
    }
    int vectorlength = addvector.size();
    for(int i = 0;i<vectorlength;i++){
        cout << i+1<<":"<<addvector[i]<<",";
    }
    subevaluate(addvector); 
    return stringrep;
}
string Expression::subevaluate(vector<string> &v){
    int totalnum = v.size();
    //This is the question, I have no idea how can i set the value totalnum
    //If it's the size of vector,it's too small. If it's the last totalnum
    //from last function. Then there is a error. In addition,I do not know
    //what the error is.
    for(int i=0;i < totalnum;i++){
        int addop = v[i].find("-");
        if(addop > 0){
            subtvector.push_back(v[i].substr(0,addop));
            string a =v[i].substr(0,addop);
            totalnum=totalnum-a.length();
            v[i] = v[i].substr(addop+1,totalnum);
        }
    }
    int vectorlength = subtvector.size();
    for(int i = 0;i<vectorlength;i++){
        cout << i+1<<":"<<subtvector[i]<<",";
    }
    return stringrep;
}

我不知道为什么我在第二个 for 循环中做错了。请帮我解决 for 循环。另外,我怎样才能将所有字符串分开。+","-","*","/".然后像计算器一样计算答案。谢谢。

此实现将不起作用...假设你有

"1+2*(3+4)"

第一次拆分(即使写得正确(将得到

  • "1"
  • "2*(3"
  • "4)"

你打算用"2*(3"做什么?

至少要用这种方法编写计算器,您需要:

  • 在前面添加"("并在末尾添加")"(即更改为"(1+2*(3+4))"
  • 查找最后一个打开括号
  • 从那里移动到第一个闭括号
  • 处理介于两者之间的内容(即 "3+4" ( 并将原始字符串中的整个括号表达式替换为结果(即从 "1+2*(3+4)""(1+2*7)" 获取(
  • 重复直到没有更多的括号

为了在给定字符上拆分字符串,您应该编写一个专用函数,例如:

std::vector<std::string> split(const std::string& text, char sep) {
    std::vector<std::string> result;
    size_t pos = text.find(sep);
    while(pos != std::string::npos) {
        result.push_back(text.substr(0, pos));
        text = text.substr(pos + 1);
    }
    result.push_back(text);
    return result;
}

然后你可以写

std::vector<std::string> res = split(text, '+');

"1+2*3+4"到包含 "1""2*3" "4" 的向量。

PS:请注意,这种计算表达式的方式不是通常所做的,但它可以工作,所以在我看来你应该继续工作,直到它完成。

我认为当您将字符串拆分为向量时,很难使代码工作。我认为,运算符优先级将很难处理。

递归过程怎么样?

通过这种方式,您可以逐步简化原始字符串。您只需继续使用子字符串调用评估函数,直到它们变成简单的表达式。

例:

exp = 12/(5+1(

呼叫

1:呼叫 F("12/(5+1("(

调用 1:f 标识子字符串"5+1"并调用自身(递归(

呼叫

2:呼叫 F("5+1"(

调用 2:简单表达式计算成返回的 "6">

调用 1:子字符串"(5+1("替换为返回的"6">

呼叫 1:exp 现在看起来"12/6">

调用 1:简单表达式计算成返回的"2">

更复杂的表达式,如"48/(5 + (2*3/(3-1(((只会导致更多的调用,以便逐步简化字符串。

代码可能类似于下面的代码。仅包含结构 - OP 填写实际代码。

bool isSimpleExpression(string& s)
{
    // Return true if s is simple, i.e. X+Y, X-Y, X*Y, X/Y
    // Otherwise false
}
string evaluateString(string& exp)
{
    while(!isSimpleExpression(exp))
    {
        // exp must be broken into smaller part as it isn't simple yet
        if (ExpContainsParanthesis() )
        {
            // Example: exp is "12/(5+1)"
            string s1 = FindSubstringInMostInnerMatchingParanthesis(exp);
            // Example: s1 is "5+1"
            // Example: call evaluateString("5+1")
            strint s2 = evaluateString(s1); // Recursive call
            // Example: s2 is 6
            ReplaceS1WithS2(exp, s1, s2);
            // Example: exp is "12/6"
        }
        else if (ExpContainsMultiplication())
        {
            // Find the substring with multiplication
            // Call this function with the substring
            // Replace the substring with the returned result 
        }
        else if ....
        {
           // division
        }
        // ... and so on
    }
    // Calculate the simple expression
    string result;
    // ..
    // ..
    return result;
}