陈志轩 • 3年前
三目运算符是啥你们自己查百度去(
首先先用一个字符串 s ,来看看有没有可以特判的(即出现 x\div0 或 b 不是"+","-","*",也不是"/")。如果有就用 s 存下对应信息并输出。
然后用一个 long long 类型的变量 ans ,用来存答案。如果出现了要特判的情况,那么将 ans 设为一个特定的值,否则直接计算。
最后用字符串 t 来存下答案(即将 ans 转为 string 类型)。如果出现了要特判的情况(即 |s| > 0 或 ans 是那个特定值)就输出空串,否则输出字符串 t 。
die码:
#include<bits/stdc++.h>
#include<windows.h>
using namespace std;
signed main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
int a,c,ans = 0;
char b;
scanf("%d%d%d",&a,&c,&b);
string s = "";
s = (c == 0 && b == '/'?"Divided by zero":"");
s = (b != '+' && b != '-' && b != '*' && b != '/'?"Invalid operator":s);
printf("%c",s);
ans = (s.size() > 0?2:(b == '+'?a + c:(b == '-'?a - c:(b == '*'?a * c:(b == '/' && c != 0?a / c:2)))));
string t = "";
while (ans){
t += (char)(ans % 10 + '0');
ans /= 10;
}
cout<<(t == "2" || s.size() > 0?"":t);
return -1;
}
评论:
#include <bits/stdc++.h>
using namespace std;
int ans;
void ddd(){cout << "Divided by zero!" << endl;}
void ddd2(){cout << "Invalid operator!" << endl;}
void bbb(){cout << ans << endl;}
signed main()
{
int a,b;
char c;
cin >> a >> c >> b;
ans = (c=='+'?a+b:(c=='-'?a-b:(c=='*'?a*b:(c=='/'?(b==0?-1:a/b):-2))));
ans==-1?ddd():(ans==-2?ddd2():bbb());
return 0;
}