【问题标题】:C beginner's problems with multiple boolean operators多个布尔运算符的 C 初学者问题
【发布时间】:2017-07-05 22:54:59
【问题描述】:

我正在寻找一种在单个表达式中使用多个布尔运算符的方法,但无法弄清楚。 下面的代码尝试将以下内容翻译成 C:

伪代码:

if 
(100 = 100) AND (10 is either 10 or 100) 
print "1"
else 
print "0"

C:

#include <stdio.h>
#include <stdbool.h>

int main(void)
{
    int num;
    num= 10;
    bool n;
    n = ((100==100) && (num == (10 || 100)));
    printf("%i", n);
}

显然我做错了什么。

【问题讨论】:

  • if ( (100==100) &amp;&amp; (num == 10 || num == 100) ) { ... } 不知道你为什么要做 100 == 100。
  • 值的100 == 100 部分有什么意义?
  • 对这些运算符的简单搜索显示了什么?你的C书怎么说?还有什么关于编程的书吗?这是基本的编程,甚至不是 C。我们不是辅导网站。
  • @twain249 确保你可以数到 100。:)
  • 此时数字并不重要。我对单个表达式 (a = b) 和 (c = (d or f) 的语法很感兴趣

标签: c boolean conditional-statements


【解决方案1】:

这个表达式

(a = b) and (c = (d or f) 

可以在 C 中的 if 语句中表示,例如

#include <iso646.h>

//...

if ( ( a == b ) and ( c == d or c == f ) ) 

或者只是喜欢

if ( ( a == b ) && ( c == d || c == f ) ) 

或者在类似的表达式语句中

#include <iso646.h>
#include <stdbool.h>

//...

bool n = ( a == b ) and ( c == d or c == f );

#include <stdbool.h>

//...

bool n = ( a == b ) && ( c == d || c == f );

【讨论】:

    【解决方案2】:

    我想我知道你想做什么,如果你只是对表达式感兴趣,那么 if 语句应该是这样的。

    if(a == b && (c == d || c == f))//It says here, IF A IS EQUAL TO B and C IS EQUAL TO D or F
    {
        printf("1");
    }
    else
    {
        printf("0");
    }
    

    不用担心花括号“{}”,您可以删除它。这只是我的爱好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-17
      • 2011-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      • 2011-05-09
      相关资源
      最近更新 更多