if语句不适用于||(或)
if statement does not work with || (or)
我是c的新手++我正试着写一个程序,但我发现它有问题即使在我使用了一个更简单的程序(下面)之后,我也无法理解
当我输入诸如85或55之类的数字时,即使程序不应该响应,它也会进行
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a=0;
cin >> a;
if(a<25 || 30<a<50 || 60<a<75)
{
cout << "see it does't workn";
}
return 0;
}
请帮我
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a=0;
cin >> a;
if(a<25 || (30<a && a<50) || (60<a && a<75))
{
cout << "see it does't workn";
}
return 0;
}
您的条件应该是:
if(a<25 || (30<a && a<50) || (60<a && a<75))
{
cout << "see it does't workn";
}
您的if语句格式不正确。
每个表达式的计算结果必须为true或false,并且不能执行上/下边界之类的操作。
试试这个:
int main()
{
int a=0;
cin >> a;
if(a<25 || (a > 30 && a < 50) || (a> 60 && a <75))
{
cout << "see it does't workn";
}
return 0;
}
尝试
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a=0;
cin >> a;
if ((a<25) || ((30<a) && (a<50)) || ((60<a) && (a<75)))
{
cout << "see it does't workn";
}
return 0;
}
圆括号是你的朋友。每个二进制条件表达式将具有左部分(a)、运算符(<)和右部分(25)。你必须把每件事都分解才能用这种方式表达出来。
下面的if语句中发生了什么:
if(a<25 || 30<a<50 || 60<a<75)
当a=85时,30总是小于a,因此为真(当转换为整数时,意味着c++中的1),然后1总是小于50,因此为true。
因此,考虑将if语句更改为
if ( a < 25 || (30 < a && a < 50) || ( 60 < a && a < 75) )
C++中没有x < z < y
类型的语句。您应该将这些语句分成二进制部分:x < z && z < y
。
让我为你重写一下:
#include <iostream>
int main() {
int a = 0;
std::cin >> a;
if(a < 25 || (30 < a && a < 50) || (60 < a && a < 75)) {
std::cout << "See? It does work!n";
}
return 0;
}
相关文章:
- OpenGL - 在 NDC 中计算位置适用于着色器,但不适用于'regular'程序
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 如何修复我的最大公约数代码?它适用于除零和零以外的所有数字
- 选择排序C++(已修改)并非适用于所有情况
- 无法让"std::enable_if"适用于无作用域枚举
- 请找出我的代码中的错误,它在提交得到错误答案的同时仍然适用于我的所有测试用例
- 确定夏令时是否适用于特定日期
- 是否有一种 STL 算法可以最后找到,但它也适用于指针?
- QT 样式表主题,适用于使用属性选择器的整个应用程序
- C++带有适用于左值和右值的引用参数的函数
- 代码适用于调试,但不适用于发布
- C++17 和更新的 std::分配器是否适用于动态数量的自定义堆?
- 适用于大型数组的无复制线程安全环形缓冲区
- NRVO 是否也适用于协程?
- 约束包容是否仅适用于概念?
- 程序只适用于包含(无副作用)cout声明
- 适用于频繁更改的大型数据集的最佳数据结构
- 相同的 for 循环适用于其他项目,但不适用于此项目。为什么?
- 多线程程序只适用于打印语句
- Switch语句只适用于某些情况