c语言计算器问题
可以实现加减乘除,如果以=开头,就引用上一个式子的计算结果,不考虑优先级(就是从左到右算1+2*4=12)但就是 以=开头 总是计算不对 哪里有错?谢谢
(注:setbuf在linux里用来清空缓冲区)
程序代码:
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int main() { double result=0.0; //calculation result char* buf=malloc(30*sizeof(char)); //input buffer int len; //length of buffer char* p_buf=NULL ; //point to buffer double num[100]; //store the operand char operator[100]; //store the operator while(1) { //the process of input setbuf(stdin,NULL); p_buf=fgets(buf,30,stdin); if(!p_buf) { printf("input error\n"); return 0; } if(strcmp(buf,"quit\n")==0) return 0; len=strlen(buf); buf[len-1]='\0'; //delete space for(int old=0,new=0;old<len;old++) { if(buf[old]!=' ') buf[new++]=buf[old]; } len=strlen(buf); //identify the result if(*buf=='=') num[0]=result; else { result=num[0]=0; operator[0]='+'; } //extract numbers char new_buf[100]; strcpy(new_buf,buf); char* p_num=strtok(buf,"-+*/^"); double each_num; int new=1; while(p_num!=NULL) { each_num=atof(p_num); num[new++]=each_num; p_num=strtok(NULL,"-+*/^"); } int how_many_num=new; //extract operators if(*new_buf=='=') { new=0; num[0]=result; } else { new=1; result=num[0]=0; operator[0]='+'; } char* p_char=strtok(new_buf,"=1234567890"); while(p_char!=NULL) { operator[new++]=*p_char; p_char=strtok(NULL,"=1234567890"); } int how_many_operator=new; result=num[0]; int i=0,j=1; for(;i<how_many_operator;i++) { switch (operator[i]) { case '+': result+=num[j];break; case '-': result-=num[j];break; case '*': result*=num[j];break; case '/': result/=num[j];break; } j++; } printf("result=%f\n",result); } }