zoukankan      html  css  js  c++  java
  • 【9108】模拟数学计算器

    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 <cstdio>
    #include <stdlib.h>
    #include <string>
    #include <iostream>
    
    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;	
    }



  • 相关阅读:
    HDU 5273 Dylans loves sequence 暴力递推
    HDU 5285 wyh2000 and pupil 判二分图+贪心
    HDU 5281 Senior's Gun 贪心
    HDU 5651 xiaoxin juju needs help 逆元
    HDU 5646 DZY Loves Partition
    HDU 5366 The mook jong
    HDU 5391Z ball in Tina Town 数论
    HDU 5418 Victor and World 允许多次经过的TSP
    HDU 5642 King's Order dp
    抽屉原理
  • 原文地址:https://www.cnblogs.com/AWCXV/p/7632339.html
Copyright © 2011-2022 走看看