【牛客網】2019多校訓練(1)J Fraction Comparision

題目鏈接:https://ac.nowcoder.com/acm/contest/881/J

題意:分數比較大小

題解:簽到題,使用C直接乘會炸 long long,可以使用Java,Python的大數,或者使用C的時候先比較分數的整數部分,再比較小數部分。

C++代碼:

#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;

int main()
{
	ll x, a, y, b;
	while (cin >> x >> a >> y >> b)
	{
		if (x / a < y / b)
		{
			cout << "<" << endl;
		}
		else if (x / a == y / b)
		{
			ll temp1 = x % a;		//小數部分大小 
			ll temp2 = y % b;
			temp1 = temp1 * b;		//交換分子後相乘 
			temp2 = temp2 * a;
			if (temp1 < temp2)
				cout << "<" << endl;
			else if (temp1 == temp2)
				cout << "=" << endl;
			else
				cout << ">" << endl;
		}
		else
		{
			cout << ">" << endl;
		}
	}
	return 0;
}

JAVA代碼:

import java.util.Scanner;
import java.math.*;
public class Main
{
    public static void main(String[]args)
    {
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext())
        {
            BigInteger x=sc.nextBigInteger();
            BigInteger a=sc.nextBigInteger();
            BigInteger y=sc.nextBigInteger();
            BigInteger b=sc.nextBigInteger();
            BigInteger ans1=x.multiply(b);
            BigInteger ans2=y.multiply(a);
            if(ans1.compareTo(ans2)<0)
                System.out.println("<");
            if(ans1.compareTo(ans2)==0)
                System.out.println("=");
            if(ans1.compareTo(ans2)>0)
                System.out.println(">");
        }
    }
}

Python:

try:
    while True:
        s=input()
        s=s.split(' ')
        if(int(s[0])*int(s[3])<int(s[1])*int(s[2])):
            print("<")
        elif(int(s[0])*int(s[3])==int(s[1])*int(s[2])):
            print("=")
        else:
            print(">")
except EOFError:
    pass

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章