
给定4个整数a,b,y和x,其中x只能是0和1。要求如下:
If 'x' is 0, Assign value 'a' to variable 'y' Else (If 'x' is 1) Assign value 'b' to variable 'y'.
注意:不允许使用任何条件运算符(包括三元运算符)或任何算术运算符(+,-,*,/)。
例如:
Input : a = 5 , b = 10, x = 1Output : y = 10Input : a = 5, b = 10 , x = 0Output : y = 5
一个想法是简单地存储“ a”和“ b”,在分别位于第0个索引和第1个索引的数组中。然后以“ x”为索引将值存储到“ y”。
下面是实现
// C/C++ program to assign value to y according // to value of x #include using namespace std; // Function to assign value to y according // to value of x int assignValue(int a, int b, int x) { int y; int arr[2]; // Store both values in an array // value 'a' at 0th index arr[0] = a; // Value 'b' at 1th index arr[1] = b; // Assign value to 'y' taking 'x' as index y = arr[x]; return y; } // Driver code int main() { int a = 5; int b = 10; int x = 0; cout << "Value assigned to 'y' is " << assignValue(a, b, x); return 0; }
输出:
Value assigned to 'y' is 5