• 2019/3/20计算器1


    转自某位大佬

    题目描述:
    给定一行表达式,中间没有空格,输出表达式的计算结果。测试数据保证在 int 范围之内。

    这是简单的一个题目,只涉及加法和减法。

    输入描述:
    一行表达式

    输出描述:
    表达式的计算结果

    样例输入:
    12+21-0

    样例输出:
    33

    #include <iostream>
    #include <string>
    #include <cstring>
    #include <cstdio>
    
    using namespace std;
    
    int str2int(string str)
    {
    	int ret = 0;
    	bool flg = (str[0]=='-');
    	for(int i = (flg==true?1:0);str[i]!='';i++)
    	{
    		if(i>0)
    			ret*=10;
    		ret+=str[i]-'0';
    	}
    	return flg==true?-ret:ret;
    }
    
    string int2str(int n)
    {
    	bool flg=(n<0);
    	
    	string ret="";
    	
    	for(n=(flg==true?-n:n);n>0;n/=10)ret=char((n%10)+'0')+ret;
    	if(flg==true)ret='-'+ret;
    	return ret;
    }
    
    int cal1(string exp)
    {	
    	int a,b,c,i,j;
    	
    	while(1)
    	{
    		bool flg=false;
    		for(int i=exp[0]=='-'?1:0;exp[i]!='';i++)if(exp[i]=='+' || exp[i]=='-')flg=true;
    		if(flg==false) return(str2int(exp));
    		
    		bool f=(exp[0]=='-');
    		
    		if(f==true)exp=exp.substr(1,exp.length()-1);
    		
    		for(i = 0;exp[i]!=''&& exp[i]!='+' && exp[i]!='-';i++)
    			continue;
    		for(j = i+1;exp[j]!=''&& exp[j]!='+' && exp[j]!='-';j++)
    			continue;
    		
    		a = str2int(exp.substr(0,i));
    		b = str2int(exp.substr(i+1,j-i-1));
    		
    		a=(f==true?-a:a);
    		
    		if(exp[i]=='-')
    			c = a-b;
    		else
    			c = a+b;
    		
    		exp=exp.substr(j,exp.length()-j);
    		exp=int2str(c)+exp;
    	}
    	
    }
    
    int main()
    {
    	char OJtmp[1001];
    	string expression;
    	while(scanf("%s",OJtmp)!=EOF)
    	{
    		expression=OJtmp;
    		cout<<cal1(expression)<<endl;
    	}
    	return 0;
    }
    
  • 相关阅读:
    二级指针与二维数组
    Linux下常用命令
    winows下使用ssh服务远程登录vbox中的虚拟机
    Shell脚本获取C语言可执行程序返回值
    memcpy与memmove的区别
    常用软件
    书目
    顺序表C语言版
    限定符【const】用法大全
    极大极小搜索和α-β剪枝
  • 原文地址:https://www.cnblogs.com/Locking-Shonn/p/12569207.html
Copyright © 2020-2023  润新知