请教一段比较两数大小的代码(不用if语句只用数学公式就可以做到)

来源:百度知道 编辑:UC知道 时间:2024/05/04 14:46:07
// Exercise 2.5 Finding the largest of two integers without comparing them.
#include <iostream>
using std::cin;
using std::cout;

int main() {

long a = 0L;
long b = 0L;

cout << "Enter a positive integer: ";
cin >> a;
cout << "Enter another different positive integer: ";
cin >> b;

// The trick is to find arithmetic expressions for each of the larger
// and the smaller of the two integers
long larger = (a*(a/b) + b*(b/a))/(a/b + b/a);
long smaller = (b*(a/b) + a*(b/a))/(a/b + b/a);
cout << "\nThe larger integer is " << larger << "."
<< "\nThe smaller integer is " << smaller << ".\n";

return 0;
}

这是一段书上的代码 代码用两个公式做到了比较大小 第一条公式求较大的数 第二条求较小的

请问有人知道这两条是什么公式吗??就是上面代码里(the longer和the sm

这里没有用到高等数学,只是用了C++里面整数变量相除的一个性质而已
整数变量相除时,结果也是整数,如果a小于b,那么结果就是0,这样就把这个数去掉了
(a*(a/b) + b*(b/a))/(a/b + b/a);
a<b时,a/b=0,所以前面为b*(b/a),后面为b/a,那么结果就是b
a=b时,a/b=1,所以前面为a+b=2a,后面为2,那么结果就是a
a>b时,b/a=0,所以前面为a*(a/b),后面为a/b,那么结果就是a
(b*(a/b) + a*(b/a))/(a/b + b/a);
这句同样的道理