问题描述
编写一个程序,以字符串方式输入一个前缀表达式,然后计算它的值。输入格式为:“运算符 对象1 对象2”,其中,运算符为“+”(加法)、“-”(减法)、“*”(乘法)或“/”(除法),运算对象为不超过10的整数,它们之间用一个空格隔开。要求:对于加、减、乘、除这四种运算,分别设计相应的函数来实现。
输入格式:输入只有一行,即一个前缀表达式字符串。
输出格式:输出相应的计算结果(如果是除法,直接采用c语言的“/”运算符,结果为整数)。
输入输出样例
样例输入
+ 5 2
样例输出
7
代码1(我信了题目中的,以字符串方式输入一个前缀表达式,这句话,就有了这AC的代码):
这里要注意当对象为10的时候
#include<iostream>
#include <string>
using namespace std;
int a[7];
int k = 0;//目的记录有几个数
void convert(string str[])//把每个字符转为int型
{
for (int i = 1; i < 3; i++)
{
for (int j = 0; j < str[i].length(); j++)
{
a[k++] = str[i][j] - '0';
}
}
}
int main()
{
string str[3];
for (int i = 0; i < 3; i++)
{
cin >> str[i];
}
if (str[0] == "+")//针对为加号时
{
convert(str);
if (k == 2)
{
cout << a[0] + a[1];
}
else if (k == 3) {
if (a[1] == 0)
{
cout << a[0] * 10 + a[1] + a[2];
}
else {
cout << a[0] + a[1] * 10 + a[2];
}
}
else {
cout << a[0] * 10 + a[1] + a[2] * 10 + a[3];
}
}
else if (str[0] == "-")//针对为减号时
{
convert(str);
if (k == 2)
{
cout << a[0] - a[1];
}
else if (k == 3) {
if (a[1] == 0)
{
cout << a[0] * 10 + a[1] - a[2];
}
else {
cout << a[0] - a[1] * 10 + a[2];
}
}
else {
cout << a[0] * 10 + a[1] - a[2] * 10 + a[3];
}
}
else if (str[0] == "*")//针对为乘号时
{
convert(str);
if (k == 2)
{
cout << a[0] * a[1];
}
else if (k == 3) {
if (a[1] == 0)
{
cout << (a[0] * 10 + a[1]) * a[2];
}
else {
cout << a[0] * (a[1] * 10 + a[2]);
}
}
else {
cout << (a[0] * 10 + a[1]) * (a[2] * 10 + a[3]);
}
}
else {//针对为除号时
convert(str);
if (k == 2)
{
cout << a[0] / a[1];
}
else if (k == 3) {
if (a[1] == 0)
{
cout << (a[0] * 10 + a[1]) / a[2];
}
else {
cout << a[0] / (a[1] * 10 + a[2]);
}
}
else {
cout << (a[0] * 10 + a[1]) / (a[2] * 10 + a[3]);
}
}
return 0;
}
代码2(巧妙的借助了输入一个数据(字符或字符串或int)之后,必须会有空格或换行其中的一种方式,才会输入下一个数据):
#include<iostream>
#include <string>
using namespace std;
int main()
{
char str;
int a, b;
cin >> str;
cin >> a;
cin >> b;
if (str == '+')//针对为加号时
{
cout << a + b;
}
else if (str == '-')//针对为减号时
{
cout << a - b;
}
else if (str == '*')//针对为乘号时
{
cout << a * b;
}
else {//针对为除号时
cout << a / b;
}
return 0;
}
欢迎任何形式的转载,但请务必注明出处。
限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。