是否有可能在没有任何比较的情况下找到最大的两个整数?我找到了一些解决方案
if(!(a/b)) // if a is less than b then division result will be zero.
{
cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now. check whether they are equal.
{
cout << "a and b are equal";
}
else
cout << "a is greater than b";
但如果(c)或if(!c)是零的比较。此外,它不适用于负数。实际上我需要一个避免任何if语句的解决方案。相反,我应该使用switch语句和算术运算符。感谢名单。
减去它们并使用令人讨厌的位杂乱黑客检查标志 http://graphics.stanford.edu/~seander/bithacks.html
如果其他程序员知道您居住的地方,请不要在生产代码中执行此操作。
试试这个,测试一下,效果很好。
public static int compare(int a, int b)
{
int c = a - b;
return (c >> 31) & 1 ^ 1;
}
我认为这种方法比其他方法更好,你可以使用这种逻辑c和java两种编程语言,但如果int是2字节则int应该是4字节然后使15字节右移而不是31字节。
enter code here
#include<stdio.h>
main()
{
int a, b;
printf("Enter three numbers\n");
scanf("%d %d", &a, &b);
printf("Largest number is %d \n",findMax( a,b ));
}
int findMax( int x, int y)
{
int z = x - y;
int i = (z >> 31) & 0x1;
printf("i = %d shift = %d \n", i, (z>>31));
int max = x - i * z;
return max;
}
在不使用比较/关系运算符的情况下获得最大数量
void PrintGreatestNumber(int a, int b)
{
int [] x = new int[] { -1, 0, 1 };
int greatestNumber = ((a+b)+ x[ 1 + ((a-b) >> 31) - (-(a-b) >> 31)] * (a-b)) /2;
Console.WriteLine(greatestNumber);
}
void greater(int a, int b) {
int c = a - b;
switch(c) {
case 0:
cout << "a and b are equal" << endl;
break;
default:
int d = c & (1<<31);
switch(d) {
case 0:
cout << "a is bigger than b" << endl;
break;
default:
cout << "a is less than b" << endl;
}
}
}
这是一个有趣的比特版本,没有任何条件分支。
int g = (int)"greater";
int l = (int)"less";
int e = (int)"equal";
int a = 7;
int b = 10;
char *result = (char*)((((a - b) >> 31) & l) | (((b - a) >> 31) & g) | ((~((a - b) | (b - a))) >> 31) & e);
cout << result;
到目前为止,问题中提出的样本或任何答案中没有一个保护不会被零除。为什么你要试图避免'if'陈述?我怀疑关于?的操作问题:运营商。
cout << "Maximum is: " << ((a>b)?a:b)
我们走了。
没有比较,不可能比较两个数字。你可以捏造它并进行间接操作,但是在一天结束时你会比较一些东西。信任编译器以优化代码并选择最佳操作。
您可能会利用计算a - b
的符号取决于哪个数字更大的事实。这用于许多比较实现中。但我相信你永远无法完全避免比较。在这种情况下,您至少需要评估处理器上符号标志的内容。
如果您只需要显示较低的数字,您还可以使用算术技巧:
result = ((a + b) - sqrt((a - b) * (a - b))) / 2
编辑呃...你被允许使用switch
?
我应该使用switch语句和算术运算符。
switch
与链式if
基本相同,因此它也使用比较。这听起来好像你应该只是比较为零,看看a - b
有什么标志。
char c;
c=0x3D + (!(b/a) && (a-b)) - (!(a/b) && (a-b));
printf("a %c b",c);
(!(a/b) ? cout << " b is greater than a" : (!(b-a) ? cout << "a and b are equal" : cout << "a is greater than b") : cout << "a is greater than b");
虽然这有点乱
编辑:这是作业吗?
我只是看不出有任何理由这样做:谁想要在没有“if”的情况下编程?
一个可能的答案是:
((a + b)+ abs(a -b))/ 2
我猜“abs”只是在某个地方隐藏了一个“if”,正如三元运算符只是“if”的另一个名字......
反常的想法:使用函数指针数组。然后使用一些算术和按位运算获取该数组的索引。
作为一个毫无意义的练习,这里是一种实现cond
函数的方法 - 为了if
的目的,假设它(和switch
和?:
)以某种方式从语言中消失,并且你正在使用C ++ 0x。
void cond(bool expr, std::function<void ()> ifTrue, std::function<void ()> ifFalse)
{
std::function<void ()> choices[2] = { ifTrue, ifFalse };
choices[expr == false]();
}
EG
cond(x > y,
/*then*/ [] { std::cout << "x is greater than y"; },
/*else*/ [] { std::cout << "x is not greater than y"; });
就像我说的,毫无意义。