条件赋值_C/C++无需使用条件运算符和算术运算符即可有条件地赋值

这篇博客介绍了如何使用C++编写一个程序,不使用条件运算符或算术运算符,通过整数x的值0或1来决定将变量a或b赋值给变量y。作者提供了一个代码片段并展示了如何存储a和b的值在数组中,然后根据x的索引获取相应值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2c129a5f39a79e4adb9344e78d299f1b.png

给定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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值