求助

B2052 简单计算器

Ac_Code_cn_com @ 2023-08-08 20:25:32

#include<bits/stdc++.h>
using namespace std;
int main(){
    int a,b;
    char c;
    cin>>a>>b>>c;
    if(c=='+')cout<<a+b;
    else if(c=='-')cout<<a-b;
    else if(c=='*')cout<<a*b;
    else if(c=='/')if(b!=0)cout<<a/b;
    else if(c=='/')if(b==0)cout<<"Divided by zero!";    
    else cout<<"Invalid operator!"; 
    return 0;
}

by luckgod @ 2023-08-08 20:39:28

invalid operator没输出


by Ac_Code_cn_com @ 2023-08-08 21:01:27

@luckgod 为啥


by Jiji2012 @ 2023-08-08 21:42:59

@WQJ111213

因为你先判断b!=0

b 不等于 0时

直接跳出 不会执行下面

参考一下

int a,b;
char c;
cin>>a>>b>>c;
if(c=='+'){
    cout<<a+b;
}
else if(c=='-'){
    cout<<a-b;
}
else if(c=='*'){
    cout<<a*b;
}
else if(c=='/'){
    if(b!=0){
        cout<<a/b;
    }else{
        cout<<"Divided by zero!";  
    }
} 
else {
    cout<<"Invalid operator!"; 
}
return 0;

by Jiji2012 @ 2023-08-08 21:43:44

@WQJ111213

别复制粘贴


|