有错吗

B2052 简单计算器

20110728qianqingwen @ 2022-03-05 10:27:04

#include <bits/stdc++.h>
using namespace std;

int main()
{

    int a,b;
    char n;
    cin>>a>>b>>n;
    switch(n)
    {
        case '+':
        cout<<a+b;  
        break;
        case '-':
        cout<<a-b;  
        break;
        case '*':
        cout<<a*b;  
        break;
        case '/':
        cout<<a/b;  
        break;
        case '%':
        cout<<a%b;  
        break;  
        default:
        cout<<"wrong";  
    }
    return 0;
}

by Justin090102 @ 2022-03-05 10:27:48


by Justin090102 @ 2022-03-05 10:28:56

@20110728qianqingwen 你这wrong是什么玩意 题目里面哪来的wrong


by CarroT1212 @ 2022-03-05 10:36:24

打代码得仔细看题目啊,评测机是不会按照你的想法来的

case '/':
        cout<<a/b;  
        break;
case '%':
        cout<<a%b;  
        break;  
default:
        cout<<"wrong";

改为:

case '/':
    if (b!=0) cout<<a/b;
     else cout<<"Divided by zero!";
    break;
default:
    cout<<"Invalid operator!"

如果出现除数为 0 的情况,则输出:

如果出现无效的操作符(即不为 +,-,*,/ 之一),则输出:Invalid operator!

%也算无效运算符。


|