记录下,主要真的怕忘,怕忘,怕忘呐!
题目:不用if,条件表达式,switch等判断语句------找出两个数中较大的
俺写的代码:
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
int a,b;
cin>>a>>b;
int max = ((a+b) + abs(a-b))/2;
cout << max <<endl;
}
这种解法就是:将两个数之间的差值求出来,当这两个数的和,加上他们之间的差值时,等同于a+b+minus(表示差值),不论是a大b小,还是b大a小,都是将小的值加上差值=较大的值,所以除以2就可以得到两数之间较大的值了。"
另外一种解法
#include <iostream>
//#include<cmath>
using namespace std;
int main()
{
int a,b;
cin>>a>>b;
/*
int max = ((a+b) + abs(a-b))/2;
cout << max <<endl;
*/
int c = a - b;
char *strs[2] = {"a比b大","b比a大"};
c = unsigned(c) >> (sizeof(int)*8 - 1);
cout << strs[c]<<endl;
}
这种解法是将两个值相减看符号位,为1则b大于a,为0则a大于b。
二进制数左数第一位(即最高位): 用0表示非负数, 用1表示负数"
脑袋不好就把他记下来,以后慢慢看嘛!!!