使用 C++ 计算包含数字、+ 和 - 的数组表达式


本题中,我们给定了一个包含 n 个字符值表示表达式的数组 arr[]。我们的任务是计算包含数字、+ 和 - 的数组表达式。

表达式仅包含数字、‘+’字符和‘-’字符。

举个例子来理解这个问题,

输入:arr = {“5”, “+”, “2”, “-8”, “+”, “9”,}

输出: 8

解释: 

表达式为 5 + 2 - 8 + 9 = 8

解决方案方法

该问题的解决方案是执行每个操作,然后返回该值。每个数字都需要转换成它等效的整数。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

一个程序来说明解决方案的工作原理:,

示例

在线演示

#include <bits/stdc++.h>
using namespace std;

int solveExp(string arr[], int n) {
   
   if (n == 0)
   return 0;
   int value, result;
   result = stoi(arr[0]);

   for (int i = 2; i < n; i += 2)
   {
      int value = stoi(arr[i]);
      if (arr[i - 1 ] == "+")
         result += value;
      else
         result -= value;
   }
   return result;
}

int main() {
   
   string arr[] = { "5", "-", "3", "+", "8", "-", "1" };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The solution of the equation is "<<solveExp(arr, n);
   return 0;
}

输出 -

The solution of the equation is 9

更新于: 2021 年 1 月 22 日

230 次浏览

职业速成

完成课程可获得认证

开始
广告