Time Limit: 10 second
Memory Limit: 2 MB问题描述
输入一个数学计算表达式,输出结果。(除法运算结果取整)Input
文件输入仅一行,输入数学表达式
Output
输出数学表达式以及结果
Sample Input1
1001+98
Sample Output1
1001+98=1099
Sample Input2
1001-98
Sample Output2
1001-98=903
Sample Input3
1001*98
Sample Output3
1001*98=98098
Sample Input4
1001/98
Sample Output4
1001/98=10
【题解】
这道题的测试点就是样例输入和输出。
就是说只有一个运算符。而且还没负数。
所以直接找到运算符的位置。
然后获取运算符左边的数字。获取运算符右边的数字。就可以了。
根据运算符做相应的运算就好了。
要用到string类的函数。
【代码】
#include#include #include #include using namespace std;string s;int main(){ getline(cin,s);//直接整行读取。 int i = 1; while (s[i]>='0' && s[i] <='9') //找到操作符的位置 i++; string s1 = s.substr(0,i); //获取操作符左边的数字 char key = s[i];//获取操作符 s = s.erase(0,i+1);//连同操作符和操作符左边的数字全都删掉。 int a = atoi(s1.c_str());//把左边的字符转换成数字 int b = atoi(s.c_str());//右边的也转换成数字(因为左边被删掉了,所以就只剩下右边了) int c; switch (key)//根据运算符,做相应的运算就可以了。 { case '+': c = a+b; break; case '-': c =a-b; break; case '*': c = a*b; break; case '/': c = a/b; break; } printf("%d%c%d=%d",a,key,b,c); //a和b的信息也都要输出。 return 0; }