如何在不使用条件语句的情况下在C++中实现三元运算符。
在下面的条件:一个? b:c
如果a为true,则将执行b。
否则,将执行c。
我们可以假设a,b和c为值。
我们可以将等式编码为:
结果=(!! a)* b +(!a)* c
在上式中,如果a为true,则结果为b。
否则,结果将为c。
C++
// CPP code to implement ternary operator
#include
// Function to implement ternary operator without
// conditional statements
int ternaryOperator(int a, int b, int c)
{
// If a is true, we return (1 * b) + (!1 * c) i.e. b
// If a is false, we return (!1 * b) + (1 * c) i.e. c
return ((!!a) * b + (!a) * c);
}
// Driver code
int main()
{
int a = 1, b = 10, c = 20;
// Function call to output b or c depending on a
std::cout << ternaryOperator(a, b, c) << '\n';
a = 0;
// Function call to output b or c depending on a
std::cout << ternaryOperator(a, b, c);
return 0;
}
Python 3
# Python 3 code to implement ternary operator
# Function to implement ternary operator
# without conditional statements
def ternaryOperator( a, b, c):
# If a is true, we return
# (1 * b) + (!1 * c) i.e. b
# If a is false, we return
# (!1 * b) + (1 * c) i.e. c
return ((not not a) * b + (not a) * c)
# Driver code
if __name__ == "__main__":
a = 1
b = 10
c = 20
# Function call to output b or c
# depending on a
print(ternaryOperator(a, b, c))
a = 0
# Function call to output b or c
# depending on a
print(ternaryOperator(a, b, c))
# This code is contributed by ita_c
PHP
Javascript
输出:
10
20
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。