gpt4 book ai didi

c - 如何从字符数组中提取运算符?

转载 作者:行者123 更新时间:2023-11-30 18:58:21 25 4
gpt4 key购买 nike

我有两个数组,其中一个包含整数,另一个包含运算符的字符。所以,假设我有以下数组:[12, 3] 和 ['+']。我想将其转换为表达式 12 + 3,它将立即计算(给我 15)。它还应该保留运算顺序,因此如果我有 [12, 3, 4] 和 ['+', '*'],它应该给我 12 + 3 * 4(即 24)。我保证字符数比整数数少一个,因此始终有正确的运算符数。在C中可以做到这一点吗?如果是这样,怎么办?

谢谢。

最佳答案

当然有可能。基本算法:

while there are operators left:
// determine operation
i = the index of the operator with the highest priority
operator = operators[i]
shift operators[i+1..end] one to the left (in other words, remove the operator from the array)
operation_function = lookup operator

// execute operation
numbers[i] = operation_function(numbers[i], numbers[i+1])
shift numbers[i+2..end] one to the left

祝你把它变成 C 语言! :)

关于c - 如何从字符数组中提取运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17040914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com