如何实施 C++中的三元算子 不使用条件语句。 在以下情况下: A.b:c 如果a为真,则b将被执行。 否则,c将被执行。 我们可以假设a、b和c为值。
null
我们可以将方程编码为: 结果=(!!a)*b+(!a)*c 在上面的等式中,如果a为真,结果将为b。 否则,结果将为c。
C++
// CPP code to implement ternary operator #include <bits/stdc++.h> // 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) << '' ; 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
<?php // PHP code to implement // ternary operator // Function to implement // ternary operator without // conditional statements function 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 ((!! $a ) * $b + (! $a ) * $c ); } // Driver code $a = 1; $b = 10; $c = 20; // Function call to output // b or c depending on a echo ternaryOperator( $a , $b , $c ) , "" ; $a = 0; // Function call to output b // or c depending on a echo ternaryOperator( $a , $b , $c ); // This code is contributed by jit_t. ?> |
Javascript
<script> // Javascript code to implement // ternary operator // Function to implement // ternary operator without // conditional statements function 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 ((!!a) * b + (!a) * c); } // Driver code let a = 1, b = 10, c = 20; // Function call to output b or c depending on a document.write( ternaryOperator(a, b, c)+ "<br>" ); a = 0; // Function call to output b or c depending on a document.write( ternaryOperator(a, b, c)+ "<br>" ); // This code is contributed by avanitrachhadiya2155 </script> |
输出:
1020
被问到: 英伟达 本文由 罗希特·塔普里亚尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END