我有后缀计算器,但他不工作,你能帮我吗?
我想计算后缀表达式2 sin 2 cos / 5 *
输出为5.000000
,但输出正确为0.17...
计算工作!
我认为问题在于向堆栈添加表达式。
谢谢你的任何建议!
const char *arrayPostfix[1000];
//.
//.
//.
//Filling the field
//field contents:
//2 <SIN> 2 <COS> </> 5 <*>
const char *stack[1000];
int counter = 0;
int i;
int numberofElement = 7; // the number of elements - 2 <SIN> 2 <COS> </> 5 <*>
char myString[100];
double help;
for (i = 0; i < numberofElement; i++) {
if (arrayPostfix[i][0] != '<') {
// IS A NUMBER
stack[counter] = arrayPostfix[i];
counter++;
} else {
// IT ISNT NUMBER
//// GET LAST OPERATOR - typedef struct
// this works
operator lastOperator;
int x = 0;
for (x = 0; x < sizeof(operatory) / sizeof(operator); x++) {
if (strcmp(arrayPostfix[i], operatory[x].nazev) == 0) {
lastOperator = operatory[x];
break;
}
}
// Operators are ok..
double n1, n2;
if (lastOperator.numberofOperators == 2) {// a+b, a-b, a*b, a/b
counter--;
n1 = atof(stack[counter]);//string to double
counter--;
n2 = atof(stack[counter]);//string to double
help = lastOperator.funkce_dvaOperator(n2, n1); // this works, calculate
sprintf(myString, "%f", help); //double to string
stack[counter] = myString;
counter++;
} else { // sin(a), cos(a)....
counter--;
n1 = atof(stack[counter]); //string to double
help = lastOperator.funkce_jedenOperator(n1); // this works, calculate
sprintf(myString, "%f", help); //double to string
stack[counter] = myString;
counter++;
}
}
return atof(stack[0]);
}
步骤进行:
1) add number 2
--------------------------------------------
Index [ 0 ] je : 2
--------------------------------------------
2) calculate sin(2)
--------------------------------------------
Index [ 0 ] je : 0.034899
--------------------------------------------
3) add number 2 - but in stac [0] is fail value..why?
--------------------------------------------
Index [ 0 ] je : 0.034899
Index [ 1 ] je : 0.034899
答案 0 :(得分:2)
这是一个非常大的问题:
sprintf(myString, "%f", help); //double to string
stack[counter] = myString;
在此设置指针stack[counter]
以指向myString
。但是您忘了myString
将始终是相同的指针,因此每当您更改myString
stack
中指向myString
的所有条目时因为它是完全相同的字符串而改变了。