C++ 比较两个整数而不进行任何比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/476800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:32:50  来源:igfitidea点击:

Comparing two integers without any comparison

c++if-statementcomparison

提问by Ameer Jewdaki

Is it possible to find the greatest of two integers without any comparison? I found some solutions:

是否有可能在没有任何比较的情况下找到两个整数中的最大值?我找到了一些解决方案:

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";

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

但是 if(c) 或 if(!c) 是与零的比较。此外,它不适用于负数。事实上,我需要一个避免任何 if 语句的解决方案。相反,我应该使用 switch 语句和算术运算符。比X。

回答by Martin Beckett

Subtract them and check the sign using nasty bit twiddling hacks
http://graphics.stanford.edu/~seander/bithacks.html

减去它们并使用令人讨厌的小技巧检查符号
http://graphics.stanford.edu/~seander/bithacks.html

Don't do this in production code if the other programmers know where you live.

如果其他程序员知道您住在哪里,请不要在生产代码中这样做。

回答by Eclipse

Here's a fun bit-twiddling version that doesn't have any conditional branches.

这是一个没有任何条件分支的有趣版本。

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;

回答by Konrad Rudolph

You might exploit the fact that the sign of the calculation a - bdepends on which number is greater. This is used in many implementations of comparison. But I believe you'll never be able to completely avoid comparison. In this case, you still at least need to evaluate the contents of the sign flag on the processor.

您可能会利用计算的符号a - b取决于哪个数字更大这一事实。这在许多比较的实现中使用。但我相信你永远无法完全避免比较。在这种情况下,您至少仍然需要评估处理器上标志标志的内容。

If you just need to display the lower number you can also use arithmetic tricks:

如果您只需要显示较低的数字,您还可以使用算术技巧:

result = ((a + b) - sqrt((a - b) * (a - b))) / 2

EDITerm … you're allowed to use switch?

编辑erm … 你可以使用switch?

I should use switch statements and arithmetic operators.

我应该使用 switch 语句和算术运算符。

switchis basically the same as chained ifand as such it also uses comparison. This sounds as if you should indeed just compare to zero to see what sign a - bhas.

switch与 chained 基本相同,if因此它也使用比较。这听起来好像您确实应该与零进行比较以查看符号a - b

回答by Konrad Rudolph

char c;
c=0x3D + (!(b/a) && (a-b)) - (!(a/b) && (a-b));
printf("a %c b",c);

回答by Adam Hawes

Not one of the samples presented in the question or any of the answers thus far protects from division by zero. Why on earth are you trying to avoid an 'if' statement? I suspect homework question about ?: operators.

到目前为止,问题中提供的任何样本或任何答案都无法防止被零除。你到底为什么要避免使用“if”语句?我怀疑有关 ?: 运算符的作业问题。

cout << "Maximum is: " << ((a>b)?a:b)

There we go.

我们走了。

It's not possible to compare two numbers without a comparison. You can fudge it and do an indirect operation, but at the end of the day you're comparing something. Trust the compiler to optimize the code and select the best operations.

没有比较就不可能比较两个数字。您可以捏造它并进行间接操作,但在一天结束时,您正在比较某些内容。相信编译器会优化代码并选择最佳操作。

回答by Vilx-

The Perverse Idea: use an array of function pointers. Then with some arithmetic and bitwise operations get an index into that array.

反常的想法:使用函数指针数组。然后通过一些算术和按位运算获得该数组的索引。

回答by fmsf

(!(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");

That gets a bit messy though

虽然有点乱

Edit: Is this homework?

编辑:这是作业吗?

回答by siukurnin

I just cant see any good reason to do that : who would want to program without "if" ?

我只是看不出有什么好的理由这样做:谁会想在没有“if”的情况下编程?

a possible answer is :

一个可能的答案是:

( ( a + b ) + abs ( a -b ) ) / 2

( ( a + b ) + abs ( a -b ) ) / 2

I guess "abs" just hides a "if" somewhere, just as the ternary operator that is just another name for "if" ...

我猜“abs”只是在某处隐藏了一个“if”,就像三元运算符只是“if”的另一个名字......

回答by Daniel Earwicker

As a pointless exercise, here's a way of implementing a condfunction - to serve the purpose of if, supposing it (and switch, and ?:) had somehow disappeared from the language, and you're using C++0x.

作为一个毫无意义的练习,这里有一种实现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]();
}

e.g.

例如

cond(x > y,
    /*then*/ [] { std::cout << "x is greater than y"; },
    /*else*/ [] { std::cout << "x is not greater than y"; });

Like I say, pointless.

就像我说的,毫无意义。

回答by user2879961

Try this, tested it, works well.

试试这个,测试它,效果很好。

public static int compare(int a, int b)
{
    int c = a - b;
    return (c >> 31) & 1 ^ 1;
}