我正在使用C语言的GMP库创建一个具有无限精度的二进制计算器.在计算后缀表达式的过程中,当我试图将结果赋给一个变量时,我遇到了错误"Assignment to Expression with ARRAY TYPE".
我搞不懂为什么结果(ans
)被视为数组,以及如何正确地将后缀表达式的值赋给ans
.evaluatePostfix
函数应该返回单个值,而不是array.
如能深入了解此错误发生的原因,并指导如何将结果正确分配给变量,我们将不胜感激.
下面是我的代码:
mpf_t evaluatePostfix(char* postfix) { //postfix func
Stack operandStack;
initializeStack(&operandStack);
int i;
mpf_t operand, op1, op2, result;
mpf_init(operand);
mpf_init(op1);
mpf_init(op2);
mpf_init(result);
for (i = 0; postfix[i] != '\0'; i++) {
char token = postfix[i];
if (isOperand(token)) {
mpf_set_str(operand, &postfix[i], 10);
push(&operandStack, operand);
while (postfix[i] != ' ') {
i++;
}
} else if (token != ' ') {
mpf_set_ui(op2, pop(&operandStack));
mpf_set_ui(op1, pop(&operandStack));
switch (token) {
case '+':
mpf_add(result, op1, op2);
break;
case '-':
mpf_sub(result, op1, op2);
break;
case '*':
mpf_mul(result, op1, op2);
break;
case '/':
if (mpf_cmp_d(op2, 0.0) != 0) {
mpf_div(result, op1, op2);
} else {
fprintf(stderr, "Error: Division by zero\n");
exit(EXIT_FAILURE);
}
break;
case '%':
fprintf(stderr, "Error: Modulo operation not supported for floating-point numbers\n");
exit(EXIT_FAILURE);
case '^':
fprintf(stderr, "Error: Exponentiation operation not supported for floating-point numbers\n");
exit(EXIT_FAILURE);
default:
fprintf(stderr, "Invalid operator\n");
exit(EXIT_FAILURE);
}
push(&operandStack, result);
}
}
mpf_clear(operand);
mpf_clear(op1);
mpf_clear(op2);
// Create a new variable to store the result and copy the value
mpf_t finalResult;
mpf_init(finalResult);
mpf_set(finalResult, result);
// Clear the original result
mpf_clear(result);
return finalResult;
}
int main() {//driver
while (1) {
struct Num* linked_list = NULL;
char temp;
printf("\nEnter infix expression: ");
while ((temp = getchar()) != '\n') {
append(&linked_list, temp);
}
char* infix = linkedListToString(linked_list);
char* postfix = (char*)malloc(strlen(infix) + 1);
infixToPostfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
mpf_t ans;
mpf_init(ans);
ans = evaluatePostfix(postfix);
gmp_printf("\nResult: %.2Ff\n", ans);
free(postfix);
free(infix);
freeLinkedList(linked_list);
printf("\nCtrl + c to exit\n");
}
return 0;
}