在用 C 语言编写简单的 FizzBuz 时,我在使用多个运算符时遇到了麻烦
#include <stdio.h>
int main(void) {
int n;
scanf("%d", &n);
if (0 < n < 10000){
for (int i = 1; i <= n; i ++) {
if (i % 15 == 0) {
puts("TikTak");
}
else if (i % 3 == 0) {
puts("Tik");
}
else if (i % 5 == 0) {
puts("Tak");
}
else {
printf("%d\n", i);
}
}
}else{
printf("-1");
}
}
现在“如果 (0 < n < 10000)" comparison operators is ignored for some reason, but if I rewrite it as:
if (n < 10000 && n > 0){
它将按预期工作。
我错过了什么吗?老实说我是 C 编程新手。哈哈
编辑:谢谢大家,哈哈,这很简单。我想这可能是我想确定的问题,因为“0 < n < 10000" is litteraly how the assigment says it should look like.
再次感谢!
重写这个条件
if (0 < n < 10000){
喜欢
if (0 < n && n < 10000){
否则原始情况看起来像
if (( 0 < n ) < 10000){
并且表达式
0 < n
的结果是 1
或 0
。所以实际上您正在将 0
或 1
与 10000
进行比较。
来自 C 标准(6.5.8 关系运算符)
6 每个运算符< (less than), >(大于)、<= (less than or equal to), and >=(大于或等于)应产生 1,如果 指定的关系为 true,如果为 false,则为 0。107) 结果有 输入 int。
表达式
0 < n < 10000
等价于 (0 < n) < 10000
,这意味着您检查 0 < n
是否小于 10000
,它始终是(像 0 < n
这样的比较结果将为 0 或 1)。