Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การประเมินนิพจน์อาร์เรย์ด้วยตัวเลข + และ - ใน C++


ปัญหา

ได้รับอาร์เรย์ arr[] ที่ประกอบด้วย n ค่าตัวอักษร แทนนิพจน์คณิตศาสตร์ ประกอบด้วยตัวเลข ตัวอักษร '+' และ '-' เท่านั้น งานคือการประเมินค่านิพจน์นี้

ตัวอย่าง

อินพุต: arr = {"5", "+", "2", "-8", "+", "9"}

เอาต์พุต: 8

คำอธิบาย: นิพจน์คือ 5 + 2 - 8 + 9 = 8

แนวทางแก้ปัญหา

วิธีแก้คือการดำเนินการทีละขั้นตอนและส่งคืนค่าผลลัพธ์ ตัวเลขแต่ละตัวต้องแปลงเป็นค่า integer

โปรแกรมตัวอย่าง

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

int solveExp(string arr[], int n) {
    if (n == 0) return 0;
    int 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