要问的问题是求RPN表达式的值,并将=作为序列的终止字符,以便程序运行RPN并计算给出的表达式。所以我遇到的一些麻烦是理解我应该如何将我的字符转换为整数,因为指令特别说使用scanf("%c",&ch),它将输入作为字符而不是整数。如何将字符转换为整型,以便将它们推入数组并对其进行相应的操作?
//
// input: 1 2 3 * + =
// output: 7
//
#include <stdio.h>
#include <stdlib.h>
int collection[100];
int top;
void push(double v){
if (top>99)
{
printf ("Stack Overflown");
exit(0);
}
collection[++top]=v;
}
double pop(){
double v;
if(top < 0)
{
printf("stack underflown");
exit(0);
}
v=collection[--top];
return v;
}
int main(void){
char ch;
double a,b,c,sum;
int i;
top=-1;
printf("Enter an RPN expression: ");
while(ch!='='){
scanf("%c", &ch);
i=0;
c=1;
push(ch);
if(collection[i]=='+'){
a=pop();
b=pop();
c=b+a;
push(c);
}
else if(collection[i]=='-'){
a=pop();
b=pop();
c=b-a;
push(c);
}
else if(collection[i]=='*'){
a=pop();
b=pop();
c=b*a;
push(c);
}
else if(collection[i]=='/'){
a=pop();
b=pop();
c=b/a;
push(c);
}
else{
while(collection[i]!=0){
i++;
}
i=i-1;
sum=0;
while(i>=0){
sum=sum+((collection[i]-48)*c);
c=c*10;
i--;
}
push(sum);
}
}
printf("%lfn",c);
}
如果满足unsigned int数字:
char ch;
scanf( "%c", &ch );
ch -= '0';
那么你可以通过乘以10并加上下一位数字来组成数字。
使用double atof(const char *nptr);
atof()
函数转换指向的字符串的初始部分由nptr
变为double
。尽管你给计算器下命令的程序结构很糟糕。算法中每个任务使用单独的函数,避免复杂性
这是我的RPN计算器:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "cal.h"
#define MAXOP 100
int main(){
int type;
double op2,op3;
char s[MAXOP];
while((type = getop(s)) != EOF){
switch(type){
case NUMBER:
push(atof(s));
break;
case 'x':
op2 = pop();
op3 = pop();
push(op2);
push(op3);
break;
case 'o':
clear();
break;
case 's':
push(sin(pop()));
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '/':
op2 = pop();
push(pop() / op2);
break;
case '%':
op2 = pop();
push((int)pop() % (int)op2);
break;
case 'n':
printf("t%.4gn",showtop());
break;
default:
printf("What was that?n");
break;
}
}
return 0;
}