基于堆栈的方式:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *postfix_to_prefix(const char *string) {
char operator, *stack[1024];
int s = 0, number, fraction;
const char *tokens = string;
while (1) {
if (sscanf(tokens, "%1d.%2d", &number, &fraction) == 2) {
stack[s] = malloc(sizeof("1.00"));
(void) sprintf(stack[s++], "%4.2f", number + (fraction/100.0));
tokens += strlen("1.00");
} else if (sscanf(tokens, "%c", &operator) == 1) {
char *operand1 = stack[--s];
char *operand2 = stack[--s];
stack[s] = malloc(strlen(operand1) + strlen(operand1) + sizeof(operator) + sizeof('\0'));
(void) sprintf(stack[s++], "%c%s%s", operator, operand1, operand2);
free(operand1);
free(operand2);
tokens += sizeof(operator);
} else {
break;
}
}
return stack[--s];
}
int main() {
const char *string = "5.335.32*6.333.22++";
printf("%s\n", string);
char *inverted = postfix_to_prefix(string);
printf("%s\n", inverted);
free(inverted);
return 0;
}
输出
> ./a.out
5.335.32*6.333.22++
++3.226.33*5.325.33
>
这是一个光秃秃的骨头实现,没有真正的错误检查,也没有其他收尾。您需要检查减法和除法等非共享操作是否按照正确的顺序与操作数一起出来,如果不是,则反转它们。
首先,'5.335.32'需要分隔符如'5.33 5.32' – BLUEPIXY
@BLUEPIXY在这种情况下所有整数都是0.00格式,这会改变什么吗? – rezon
我明白了。但我认为这需要额外的努力。 – BLUEPIXY