C 带三元运算符的返回布尔值

C 带三元运算符的返回布尔值,c,C,我编写这段代码是为了知道我的输入是否是2的倍数 #include <stdio.h> #include <stdlib.h> #include <unistd.h> bool main(int ac, char **av) { if (ac == 2) { int nb = atoi(av[1]); (((nb / 2) * 2) != nb) ? false : true; } } 我正在使用UbuntuBas

我编写这段代码是为了知道我的输入是否是2的倍数

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

bool    main(int ac, char **av)
{
  if (ac == 2)
  {
      int nb = atoi(av[1]);
      (((nb / 2) * 2) != nb) ? false : true; 
  }
}
我正在使用UbuntuBash for Windows(我现在没有访问任何Linux)


我不明白为什么我的函数不能使用bool类型,或者为什么“false”和“true”不能被识别

(((nb / 2) * 2) != nb) ? false : true; 
你可以随时使用

!(((nb / 2) * 2) != nb)
(ofc==nb也会起作用)


如果编译器不能识别真假,那么很可能你的代码有问题,可能是你破坏了语法,或者是让编译器发疯了,它会抛出这种错误。看不到任何其他原因所以你的代码中有很多问题

首先,您错过了此处的
return
关键字:

return (((nb / 2) * 2) != nb) ? false : true;
^^^^^^
除此之外,你不需要三元运算符,因为第一部分已经准备好了。因此,只要做:

return (((nb / 2) * 2) == nb);
^^^^^^                 ^^
此外,当
ac
不等于2时,代码中没有
return
语句

您还应该包括
stdbool.h
以使用
bool

最后,
main
函数必须返回
int
——而不是
bool

对代码的重写可以是:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>   // Include this to use bool

bool foo(int ac, char **av)
{
  if (ac == 2)
  {
      int nb = atoi(av[1]);
      return (((nb / 2) * 2) == nb); 
  }

  return false;
}

int main(int ac, char **av)
{
    if (foo(ac, av))
    {
        printf("foo returned true\n");
    }
    else
    {
        printf("foo returned false\n");
    }

    return 0;
}
#包括
#包括
#包括
#include//include this使用bool
布尔富(内部ac,字符**av)
{
如果(ac==2)
{
int nb=atoi(av[1]);
返回(((nb/2)*2)=nb);
}
返回false;
}
内部主(内部ac,字符**av)
{
如果(foo(ac,av))
{
printf(“foo返回true\n”);
}
其他的
{
printf(“foo返回false\n”);
}
返回0;
}

您缺少
return
语句。还包括
stdbool.h
以使用
bool
main
不会返回
bool
。考虑到您在这个简短程序中遇到的问题的数量,您最好先阅读您的书。C规范规定
main
必须返回
int
。您可以将
((nb/2)*2)!=nb)
简化为
nb&1
。答案缺少关于
stdbool.h
的一个重要部分。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>   // Include this to use bool

bool foo(int ac, char **av)
{
  if (ac == 2)
  {
      int nb = atoi(av[1]);
      return (((nb / 2) * 2) == nb); 
  }

  return false;
}

int main(int ac, char **av)
{
    if (foo(ac, av))
    {
        printf("foo returned true\n");
    }
    else
    {
        printf("foo returned false\n");
    }

    return 0;
}