题解 | #简单计算器#
简单计算器
https://www.nowcoder.com/practice/b8f770674ba7468bb0a0efcc2aa3a239
#include <cstdlib> #include <iomanip> #include <iostream> #include <string> using namespace std; int main() { int i=0, b=0,n=0; string calc; string num1,num2,op; getline(cin, calc);//直接cin出现空格会中断,使用getline函数,跳过空格中断,将空格计入字符串 while (calc[i]!='\0') { if(calc[i]=='+')//判断是不是合法的运算符号,并用b作为标志位记录相应的运算 { b=1; n=i; } else if(calc[i]=='-') { b=2; n=i; } else if(calc[i]=='*') { b=3; n=i; } else if(calc[i]=='/') { b=4; n=i; } else if((calc[i]<48||calc[i]>57)&&calc[i]!='.') { b=0; n=i; } i++; } num1 = calc.substr(0,n);//将输入的字符串里数字的部分分割出来 int len=calc.length();//重点在于确定运算符的位置便于进行分割 num2 = calc.substr(n+1,len+1);//裁剪第二个运算数字 double number1=stod(num1);//将字符串转换double类型的数据 double number2=stod(num2); if(number2-0.0<1e-10)//对第二位数进行判断,若为0则按非法输入判断 { b=5; } switch (b) { case 0:cout<<"Invalid operation!";break; case 1:cout<<setprecision(4)<<fixed<<number1<<"+"<<number2<<"="<<number1+number2;break; case 2:cout<<setprecision(4)<<fixed<<number1<<"-"<<number2<<"="<<number1-number2;break; case 3:cout<<setprecision(4)<<fixed<<number1<<"*"<<number2<<"="<<number1*number2;break; case 4:cout<<setprecision(4)<<fixed<<number1<<"/"<<number2<<"="<<number1/number2;break; case 5:cout<<"Wrong!Division by zero!";break; } } // 64 位输出请用 printf("%lld")