您的位置:首页 > 其它

简单计算器的实现

2018-01-28 22:41 92 查看
题目描述:

读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。

输入:

测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。

输出:

对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。

样例输入:

1 + 2

4 + 2 * 5 - 7 / 11

0

样例输出:

3.00

13.36

//先用自己想到的思路写了如下一堆,有点啰嗦和繁杂。

//看到网上其他人写的简介的代码,希望自己之后能学习和优化。

//加减乘除的功能实现了,但是输出是整形的,不符合题目中要求的保留两位小数。

#include <iostream>
#include<vector>
#include<string>
#include<iomanip>
using namespace std;
string delspace(string temp)
{
int begin = 0;
begin = temp.find(" ", begin);
while (begin != -1)
{
temp.replace(begin, 1, "");
begin = temp.find(" ", begin);
}
return temp;
};
int main()
{
vector<string> input;
string num;
while (getline(cin, num)&&num!="0")
{
input.push_back(num);
};
vector<string>::iterator it;
for (it = input.begin(); it != input.end(); it++)
{
string temp;
temp = *it;
temp = delspace(temp);
//cout << temp << endl;
int len = temp.size();
for (int i = 0; i < len; i++)
{
if (temp[i] == '*' | temp[i] == '/')
{
if(temp[i] == '*')
temp[i] = (temp[i - 1] - 48)*(temp[i + 1] - 48)+48;
else
temp[i] = (temp[i - 1] - 48)/(temp[i + 1] - 48)+48;
temp[i - 1] = 32;
temp[i + 1] = 32;
temp = delspace(temp);
len = len - 2;
i = i - 1;
}
}
//cout << temp << endl;
len = temp.size();
for (int i = 0; i < len; i++)
{
if (temp[i] == '+' | temp[i] == '-')
{
if (temp[i] == '+')
temp[i] = (temp[i - 1] - 48)+(temp[i + 1] - 48) + 48;
else
temp[i] = (temp[i - 1] - 48)-(temp[i + 1] - 48) + 48;
temp[i - 1] = 32;
temp[i + 1] = 32;
temp = delspace(temp);
//cout << temp << endl;
len = len - 2;
i = i - 1;
}
}
if (temp[0]>57)
{
int s = temp[0] - 48;
cout << s << endl;
}
else
cout << temp<< endl;

}
return 0;
}


char型和int型相互转换:

一、将0到9之间的数字转化为char类型的,或是将’0’-‘9’之间的字符转化为int型的数字。

用强制转换的话可以这样:(0的ASCII码是48)

int a;

char b;

a=(int)(b-48);或b=(char)(a+48);

//这样转化的前提是a的范围是0-9,b的范围是‘0’-‘9’

别人家的代码总是辣么好看。。。。

#include "stdio.h"
#include "string.h"
#define MAX 1001

double stack[MAX];
int tail;

int main(){
int a;
while(scanf("%d ",&a)&&a!=0){
tail=0;
stack[++tail]=1.0*a;//tail始终指向末尾数字位置
//1.入栈所有数据(如果遇到*/号,只更新栈尾)
char ch1,ch2;
while(scanf("%c %d%c",&ch1,&a,&ch2)!=EOF){
if(ch1=='+'){
stack[++tail]=1.0*a;//push
}else if(ch1=='-'){
stack[++tail]=-1.0*a;//push neg
}else if(ch1=='*'){
stack[tail]=stack[tail]*a;//upd
a199
ate tail
}else if(ch1=='/'){
stack[tail]=stack[tail]/(double)a;//updata tail
}
if(ch2!=' ')
break;
}
//2.把栈里头的东西全部加起来,求和
double result=0;
for(int i=1;i<=tail;i++)
result+=stack[i];
printf("%.2lf\n",result);
}
return 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: