题目描述
根据输入的运算符对输入的整数进行简单的整数运算。 运算符只会是加+、减-、乘*、除/、求余%、阶乘!六个运算符之一。 输出运算的结果,如果出现除数为零,则输出“error”,如果求余运算的第二个运算数为0,也输出“error”。
输入描述:
输入为一行。先输入第一个整数,空格输入运算符,然后再空格输入第二个整数,回车结束本次输入。
如果运算符为阶乘!符号,则不输入第二个整数,直接回车结束本次输入。
输出描述:
可能有多组测试数据,对于每组数据,
输出一行。输出对输入的两个(或一个)数,根据输入的运算符计算的结果,或者“error”。
示例1
输入
12 + 34
54 - 25
3 * 6
45 / 0
5 !
34 % 0
输出
46
29
18
error
120
error
题目解析:除了!其他只有两个数字进行运算,注意非法,除0.
代码:
#include<bits/stdc++.h>
int main(){
int a,b;
char c;
while(scanf("%d %c",&a,&c)!=EOF)
if(c!='!'){
scanf("%d",&b);
switch(c){
case '+':printf("%d\n",a+b);
break;
case '-':printf("%d\n",a-b);
break;
case '*':printf("%d\n",a*b);
break;
case '/':if(b!=0)
printf("%d\n",a/b);
else
printf("error\n");
break;
case '%':if(b!=0)
printf("%d\n",a%b);
else
printf("error\n");
break;
}
}
else{
int s=1;
for(int i=2;i<=a;i++)
s=s*i;
printf("%d\n",s);
}
}
/*
//做字符串输入太多了,有点懵,OJ会溢出。
//所以可以了解。
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<vector>
#include<map>
#include<iomanip>
using namespace std;
int main()
{
string function;
char fuhao;
while(getline(cin , function)){
if(function.find("+") != string::npos){ //取符号
fuhao = '+';
}else if(function.find("-") != string::npos){
fuhao = '-';
}else if(function.find("*") != string::npos){
fuhao = '*';
}else if(function.find("/") != string::npos){
fuhao = '/';
}else if(function.find("%") != string::npos){
fuhao = '%';
}else if(function.find("!") != string::npos){
fuhao = '!';
}
int number1 = 0,number2 = 0,index; //取数字
int sum = 1;
vector<int> vc;
while((index = function.find(" ",index)) != string::npos){ //非阶乘查找所有空格
vc.push_back(index);
index++;
}
int count = 0;
for(int i = vc[0] - 1;i >= 0;i--){
number1 += (function[i] - '0') * pow(10,count);
count++;
}
count = 0;
for(int i = function.size() - 1;i > vc[1];i--){
number2 += (function[i] - '0') * pow(10,count);
count++;
}
//按符号计算
int countmark = 0;
int numbermark=0;
int indexmark;
switch(fuhao){
case '!':
indexmark = function.find(" ");
for(int i = indexmark - 1;i >= 0 ;i--){
numbermark += (function[i] - '0') * pow(10,countmark);
countmark++;
}
for(int i = 2 ;i <= numbermark; i++){
sum *= i;
}
cout << sum << endl;
break;
case '+':
cout << number1 + number2 << endl;
break;
case '-':
cout << number1 - number2 << endl;
break;
case '*':
cout << number1 * number2 << endl;
break;
case '/':
if(number2 != 0){
cout << number1 / number2 << endl;
}else{
cout << "error" << endl;
}
break;
case '%':
if(number2 != 0){
cout << number1 % number2 << endl;
}else{
cout << "error" << endl;
}
break;
}
vc.clear();
cin.ignore();
}
return 0;
}
*/