ljx201129 @ 2024-07-22 21:20:27
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a, b;
char c;
cin >> a >> b >> c;
if (c != '+' && c != '-' && c != '*' && c != '/' )
{
cout << "Invalid operator!";
return 0;
}
if (c = '+')
{
cout << a+b;
return 0;
}
if (c = '-')
{
cout << a-b;
return 0;
}
if (c = '*')
{
cout << a*b;
return 0;
}
if (c = '/')
{
if (b = 0)
{
cout << "Divided by zero!";
return 0;
}
else
{
cout << a/b;
return 0;
}
}
return 0;
}
by are_you_sure @ 2024-07-22 21:24:46
@ljx201129 条件判断要用==
,=
是赋值
by are_you_sure @ 2024-07-22 21:25:27
把每个if
里面的=
改成==
即可
by are_you_sure @ 2024-07-22 21:28:04
#include <iostream>
using namespace std;
int main()
{
int a, b;
char c;
cin >> a >> b >> c;
if (c != '+' && c != '-' && c != '*' && c != '/' )
{
cout << "Invalid operator!";
return 0;
}
if (c == '+')
{
cout << a+b;
return 0;
}
if (c == '-')
{
cout << a-b;
return 0;
}
if (c == '*')
{
cout << a*b;
return 0;
}
if (c == '/')
{
if (b == 0)
{
cout << "Divided by zero!";
return 0;
}
else
{
cout << a/b;
return 0;
}
}
return 0;
}
其实你写的代码算很工整的了,我都写不出来这么工整的
by are_you_sure @ 2024-07-22 21:35:03
给你介绍一种很好用的算法:
switch(/*变量*/){
case /*值*/:/*操作*/;break;
default:/*操作*/;break;
}
```cpp
switch(c){
case '+':cout<<a+b;break;
case '-':cout<<a-b;break;
default :cout<<"UNKNOW";break;
}
相当于
if(c=='+'){
cout<<a+b;
}
if(c=='-'){
cout<<a-b;
}
else{
cout<<"UNKNOW";
}
by Obijeb @ 2024-07-22 21:36:22
@are_you_sure 然后就会一不小心忘写break导致死循环()
by are_you_sure @ 2024-07-22 21:36:40
给你介绍一种很好用的算法:
switch(/*变量*/){
case /*值*/:/*操作*/;break;
default:/*操作*/;break;
}
下面
switch(c){
case '+':cout<<a+b;break;
case '-':cout<<a-b;break;
default :cout<<"UNKNOW";break;
}
相当于
if(c=='+'){
cout<<a+b;
}
if(c=='-'){
cout<<a-b;
}
else{
cout<<"UNKNOW";
}
by are_you_sure @ 2024-07-22 21:42:35
@Obijeb 额,不会死循环,只会挨个判断一遍,好像还会无脑全部执行一遍
by wisjsks @ 2024-07-24 12:37:46
if(xxxx=xxxx) {
xxxxxxxxxx;
xxxxxx;
} 里的“=”应换成“==”
if(xxxx==xxxx)
{
xxxxxxxxxx;
xxxxxx;
}
by Jason101 @ 2024-08-08 20:58:48
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a,b; char c;
cin >> a >> b >> c;
if(c != '+'&&c != '-'&&c != '*'&&c != '/')
{
cout << "Invalid operator!";
}
else
{
int plus;
if(c == '+')
{
plus = a + b;
cout << plus;
}
int m;
if(c == '-')
{
m = a - b;
cout << m;
}
int mul;
if(c == '*')
{
mul = a * b;
cout << mul;
}
int ti;
if(c == '/')
{
if(b == 0)
{
cout << "Divided by zero!";
}
else
{
ti = a / b;
cout << ti;
}
}
}
return 0;
}
by zhangfengyao @ 2024-08-23 14:53:07
#include<iostream>
using namespace std;
int main()
{
int a,b;
char v;
cin>>a>>b>>v;
if(v=='+')
{
cout<<a+b<<endl;
}
else if(v=='-')
{
cout<<a-b<<endl;
}
else if(v=='*')
{
cout<<a*b<<endl;
}
else if(v=='/')
{
if(b==0)
{
cout<<"Divided by zero!"<<endl;
}
else
{
cout<<a/b<<endl;
}
}
else
{
cout<<"Invalid operator!"<<endl;
}
return 0;
}