题解:AT_past202212_b 分数比較

· · 题解

题意:

输入两个分数,比较大小。

思路:

由基础数学知识得:

  1. 当 \frac{a}{b} \ge \frac{c}{d} \ge 0 时,有 a \times d \ge b \times c。
  2. 当 \frac{a}{b} \le \frac{c}{d} \le 0 时,有 abs(b \times c) \le abs(a \times d)。

所以只需定义变量 f 记录 \frac{a}{b} 和 \frac{c}{d} 的正负,再判断 a \times d 和 b \times c 的大小即可。

Code:

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int a,b,c,d;
    cin >> a >> b >> c >> d;
    bool f = false;
    if(a * b < 0 && c * d < 0) //判断正负 
        f = true;
    if(abs(a * d) < abs(b * c))
        if(!f)
            cout << "<";
        else 
            cout << ">";
    else if(a * d == b * c)
        cout << "=";
    else 
        if (!f)
            cout << ">";
        else
            cout << "<";
    return 0;
}