一个简单的四则运算计算器,支持小数、求余、求幂、使用运算结果连续计算等功能。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | //Powered by TCreopargh #include<stdio.h> #include<string.h> #include<stdlib.h> #include<math.h> int main(int argc, char *argv[]) { char first[400],last[400],Ans[]="ans",Quit[]="quit",Reset[]="reset"; double a,b,result=0,ans=0; int opPos=0,operatorExist,i,k; char input[800]; char op; puts("/////////////////////////////"); puts("// Simple Calculator //"); puts("/////////////////////////////"); puts("Input two numbers containing an operator between them."); puts("e.g. input \"5*4\" to calculate 5 multiplied by 4."); puts("Input \"ans\" instead of a number to use the result of the previous calculation."); puts("Input \"quit\" to exit the program."); puts("Input \"reset\" to reset the program."); while(1) { memset(first,0,sizeof(first)); memset(last,0,sizeof(last)); i=0; k=0; operatorExist=0; gets(input); if(!strcmp(input,Quit)) break; if(!strcmp(input,Reset)) { system("cls"); puts("/////////////////////////////"); puts("// Simple Calculator //"); puts("/////////////////////////////"); puts("Input two numbers containing an operator between them."); puts("e.g. input \"5*4\" to calculate 5 multiplied by 4."); puts("Input \"ans\" instead of a number to use the result of the previous calculation."); puts("Input \"quit\" to exit the program."); puts("Input \"reset\" to reset the program."); ans=0; continue; } while(input[i]!='\0') { if(input[i]=='+'||input[i]=='-'||input[i]=='*'||input[i]=='/'||input[i]=='%'||input[i]=='^') { op=input[i]; opPos=i; operatorExist=1; break; } i++; } if(!operatorExist) { if(!strcmp(input,Ans)) result=ans; else result=atof(input); ans=result; if(result-(int)result==0) printf("=%d\n",(int)result); else printf("=%.6lf\n",result); puts("Your input does not contain an operator. Please enter the expression correctly."); continue; } strncpy(first,input,opPos); for(i=opPos+1; input[i]!='\0'; i++) { last[k]=input[i]; k++; } if(!strcmp(first,Ans)) a=ans; else a=atof(first); if(!strcmp(last,Ans)) b=ans; else b=atof(last); switch (op) { case '+': result=a+b; break; case '-': result=a-b; break; case '*': result=a*b; break; case '/': if(b==0) { puts("ERR: cannot devide a number by 0."); continue; } result=a/b; break; case '%': if(b==0) { puts("ERR: cannot devide a number by 0."); continue; } result=(int)a%(int)b; break; case '^': result=pow(a,b); break; default: puts("Invalid imput. Please try again."); continue; } if(result-(int)result==0) printf("=%d\n",(int)result); else printf("=%.6lf\n",result); ans=result; } return 0; } |
发表回复