Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 寻找不使用if语句的等价函数_C_Function_If Statement - Fatal编程技术网

C 寻找不使用if语句的等价函数

C 寻找不使用if语句的等价函数,c,function,if-statement,C,Function,If Statement,我有这个函数 int f(int x) { if (x == 0) return 0; return 1; } 是否可以在不使用if语句的情况下编写等效函数?您可以这样做: return x ? 1 : 0; 您可以这样做: return x ? 1 : 0; 只需写:返回x!=0……只需写:返回x!=0..…该函数将x转换为布尔值 您可以使用三元运算符,而不是if语句: int f(int x) { return x ? 1 : 0; } 有更简单的方法可以做到这一点:

我有这个函数

int f(int x) {
  if (x == 0)
    return 0;
  return 1;
}

是否可以在不使用
if
语句的情况下编写等效函数?

您可以这样做:

return x ? 1 : 0;

您可以这样做:

return x ? 1 : 0;

只需写:
返回x!=0
……

只需写:
返回x!=0
..…

该函数将
x
转换为布尔值

您可以使用三元运算符,而不是
if
语句:

int f(int x) { return x ? 1 : 0; }
有更简单的方法可以做到这一点:

int f(int x) { return x != 0; }

int f(int x) { return !!x; }
您甚至可以使用C99
bool
类型,但它有点容易出错:

#include <stdbool.h>
int f(int x) { return (bool)x; }
#包括
intf(intx){return(bool)x;}
以下是一些有趣的选择:

int f(int x) { return x>0|0>x; }
int f(int x) { return x<0|0<x; }
intf(intx){返回x>0 | 0>x;}

int f(int x){return x函数将
x
转换为布尔值

您可以使用三元运算符,而不是
if
语句:

int f(int x) { return x ? 1 : 0; }
有更简单的方法可以做到这一点:

int f(int x) { return x != 0; }

int f(int x) { return !!x; }
您甚至可以使用C99
bool
类型,但它有点容易出错:

#include <stdbool.h>
int f(int x) { return (bool)x; }
#包括
intf(intx){return(bool)x;}
以下是一些有趣的选择:

int f(int x) { return x>0|0>x; }
int f(int x) { return x<0|0<x; }
intf(intx){返回x>0 | 0>x;}

int f(int x){return x
return x!=0
有很多选项。你可以使用三元运算符。你可以按照@williampersell说的做。你可以返回
float(x)=-float(x)
。你的实际目标是什么?听起来像是没有任何初始投入的家庭作业帮助。如果你想强调这是一个毫无意义的家庭作业问题,你也可以用
替换
if
,而
则可以。
返回x!=0
有很多选项。你可以使用三元运算符。你可以做@williamper卖出。你可以返回
float(x)==-float(x)
。你的实际目标是什么?听起来像是没有任何初始投入的家庭作业帮助。如果你想强调这是一个毫无意义的家庭作业问题,你也可以用
替换
if
。我很好奇这是否依赖于实现。此操作将返回
bool
。返回v函数的值最终会将类型提升为
int
。但C仍然将
true
定义为不同于
0
@MarcoRamírez“此操作将返回布尔值”,no.
x!=0
是一个
int
,在C中。没有
bool
\u bool
涉及
返回x!=0
。我很好奇这是否依赖于实现。此操作将返回
bool
。函数的返回值最终将该类型提升为
int
。但是ill C只是将
true
定义为不同于
0
@MarcoRamírez“此操作将返回bool”,不。
x!=0
是一个
int
,在C中。没有
bool
\u bool
涉及
返回x!=0
。我只是好奇:
返回(bool)有什么容易出错的地方x、 
?@MartinR:演员阵容为
(bool)
仅适用于标准的
bool
,或者更准确地说,C99中引入的
\u bool
类型。如果
bool
定义为
typedef unsigned char bool;
typedef int bool;
,就像某些C99之前的环境一样,它将以静默方式失败。因此,这种构造是不直观的,可能只是简单的我只是好奇:
return(bool)x;
容易出错吗?@MartinR:cast to
(bool)
仅适用于标准的
bool
,或者更准确地说,C99中引入的
\u bool
类型。如果
bool
定义为
typedef unsigned char bool;
typedef int bool;
,就像某些C99之前的环境一样,它将以静默方式失败。因此,这种构造是不直观的,可能只是简单的必须避免。