C++ 四则运算
来源:互联网 发布:网络拓扑结构图软件 编辑:程序博客网 时间:2024/06/07 03:00
题目大意:有字符串表示的一个四则运算表达式,要求计算出该表达式的正确数值。四则运算即:加减乘除"+-*/",另外该表达式中的数字只能是1位(数值范围0~9)。另若有不能整除的情况,按向下取整处理,eg: 8/3得出值为2。
若有字符串"8+7*2-9/3",计算出其值为19。
主要考点:
1. 数字的字符形式变换为数字形式的方法;
2. 数字的数字形式变换为数字的字符串形式的方法。
<span style="font-family: Arial, Helvetica, sans-serif;">#include <iostream></span>
#include <string>using namespace std;void cq(string& str){int npos1,npos2,npos,result;npos1=str.find("*");npos2=str.find("/");if(npos1<0 && npos2<0)return;if(npos1>0 && npos2>0) //乘除运算{npos= npos1<npos2 ? npos1:npos2;}else if(npos1<0 && npos2>0) //乘除运算{npos=npos2;}else if(npos1>0 && npos2<0) //乘除运算{npos=npos1;}int i=npos-1;char temp[10];int j=0;while(i>=0 && str[i]>='0' && str[i]<='9'){temp[j++]=str[i];temp[j]='\0';i--;}//反转int lent=strlen(temp);for(int k=0;k<(lent+1)/2;k++){int Temp=temp[k];temp[k]=temp[lent-1-k];temp[lent-1-k]=Temp;}int a=atoi(temp); int pos=++i;//记录开始被替换的位置。 i=npos+1; j=0;while(i<str.length() && str[i]>='0' && str[i]<='9'){temp[j++]=str[i];temp[j]='\0';i++;} int b=atoi(temp);//i为替换的结束的下一位置。if(str[npos]=='*')result=a*b;elseresult=a/b;char r[5];itoa(result,r,10); string re=r;str.replace(pos,i-pos,re);npos1=str.find("*");npos2=str.find("/");if(npos1>0 || npos2>0)cq(str);}void jj(string& str){ int npos1,npos2,npos,result;npos1=str.find("+");npos2=str.find("-");if(npos1<0 && npos2<0)return;if(npos1>0 && npos2>0) //乘除运算{npos= npos1<npos2 ? npos1:npos2;}else if(npos1<0 && npos2>0) //乘除运算{npos=npos2;}else if(npos1>0 && npos2<0) //乘除运算{npos=npos1;}int i=npos-1;char temp[10];int j=0;while(i>=0 && str[i]>='0' && str[i]<='9'){temp[j++]=str[i];temp[j]='\0';i--;}//反转int lent=strlen(temp);for(int k=0;k<(lent+1)/2;k++){int Temp=temp[k];temp[k]=temp[lent-1-k];temp[lent-1-k]=Temp;}int a=atoi(temp);int pos=++i; i=npos+1; j=0;while(i<str.length() && str[i]>='0' && str[i]<='9'){temp[j++]=str[i];temp[j]='\0';i++;} int b=atoi(temp);if(str[npos]=='+')result=a+b;elseresult=a-b;char r[5];itoa(result,r,10); string re=r;str.replace(pos,i-pos,re);npos1=str.find("+");npos2=str.find("-");if(npos1>0 || npos2>0)jj(str);}void fun(string &str){cq(str);jj(str);}void main(){string str="8+7*2-9/3";fun(str);cout<<str<<endl;while(cin>>str){fun(str);cout<<str<<endl;}//加减运算}
0 0
- 四则运算 c/c++ 栈
- 四则运算(C语言)
- C语言实现四则运算
- C语言编译四则运算
- 大数四则运算c
- Object-C,四则运算计算器
- c语言加减乘除, 四则运算
- 大数四则运算(C语言)
- C/C++ 实现整数四则运算
- 数据结构,C语言实现四则运算
- 大数之四则运算(C++)
- 有理数的四则运算 C、java
- C/C++带括号四则运算
- 分数的四则运算(c++)
- C/C++带括号四则运算
- c语言版——四则运算
- C语言-大整数四则运算
- C:static变量调用:四则运算
- 变量 地址 值
- MySQL数据库常用操作语句大全
- 设计模式 - 代理模式(proxy pattern) 未使用代理模式 详解
- Caused by: java.lang.ClassNotFoundException: org.jbpm.pvm.internal.processengine.SpringHelper
- Flyweight 设计模式
- C++ 四则运算
- ubuntu12.04 64bit 安装nodeJS
- sphinx 增量索引 实现近实时更新
- linux shell 脚本命令操作案例大全
- sublime text如何安装ctags来定位函数
- 详解YUV数据格式
- 修改maven本地仓库的位置及疑惑
- Struts2多个文件上传的分析及源代码说明
- poj 1847 dijkstra(搬道岔的最少次数)