Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
有没有一种简单的方法来查看一个整数是否在一个范围内?
像
int x = 15; if(x==1x) { std::cout << "Yes it falls in the range 10-19" << std::endl; }
据我了解,最接近的是
((x>9) && (x<20))?(std::cout << "Yes" << std::endl):(std::cout << "No" << std::endl);
或类似的东西。
有类似第一种方式的吗?
不,除了您拥有的第二个版本之外别无他法。
如果您要使用我会使用的包容性范围,>=并且<=(在我看来)它更适合范围检查。if然而,在 C++ 中,除了使用or?:和 and的条件&&表达式之外,没有聪明的方法来检查范围。
>=
<=
if
?:
&&