简体   繁体   English

用运算符判断真假

[英]True and False with Operators

me again... Sorry for asking maybe a little bit stupid questions but i am a starter and i really want to learn coding.. So i got a problem to realize why those are always true?又是我...很抱歉问了一些愚蠢的问题,但我是初学者,我真的很想学习编码..所以我有一个问题要意识到为什么这些总是正确的? Its something with the operators or again C behavior is undefined.它与操作员有关,或者 C 行为未定义。 ? ?

   int x;
   int b;
   b = 1 < x < 10;
   printf("%d%d",b);
    char c = 'z';
    (c==' ') || (c='\t') || (c=='\n');
    printf("%c",c);

Why those are always true?为什么那些总是正确的? Its because of ASCII code or what?是因为ASCII码还是什么?

Result of comparison of constant 10 with boolean expression is always true常数 10 与 boolean 表达式的比较结果始终为真

You can see here a table for the C Operator Precedences it could be read like this:您可以在此处查看 C 运算符优先级的表格,可以这样阅读:

b = ((1 < x) < 10);

being that in languages such as C, relational operators return the integers 0 or 1, where 0 stands for false and any non-zero value stands for true.因为在 C 等语言中,关系运算符返回整数 0 或 1,其中 0 代表假,任何非零值都代表真。

so the value stored in b is 1 (true)所以存储在 b 中的值为 1(真)

Also:还:

you're not initializing x , it should have trash info (probably != false)你没有初始化x ,它应该有垃圾信息(可能!= false)

and in your second code, you're allocating instead of comparing, (c='\t') is this on purpose?在你的第二个代码中,你是在分配而不是比较, (c='\t')这是故意的吗? That's the reason it's printing a 'tab'.这就是它打印“标签”的原因。

In your first block of code, there are several problems:在您的第一个代码块中,有几个问题:

  1. x is uninitialized (you did not give it a value) x未初始化(你没有给它一个值)
  2. 1 < x < 10 is not valid C 1 < x < 10无效 C
  3. your printf statement expects 2 integer values to accompany the "%d%d", but you are only passing 1您的 printf 语句需要 2 个 integer 值伴随“%d%d”,但您只传递 1

I think this is what you want:我认为这就是你想要的:

int x = <some valid value>;
int b;
b = ((1 < x) && (x < 10)); // expression is true if x is between [2..9]
printf("%d",b);

This line这条线

(c==' ') || (c='\t') || (c=='\n');

Should be应该

(c==' ') || (c=='\t') || (c=='\n');

Note the double equals when comparing to \t (the tab character).\t (制表符)进行比较时,请注意双等号。 Otherwise, you wind up assigning a tab char to c .否则,您最终会为c分配一个制表符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM