比较两个分数(< 和朋友) [英] Comparing two fractions (< and friends)

查看:23
本文介绍了比较两个分数(< 和朋友)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢比较两个分数.它们的存储方式如下:

I have two fractions I like to compare. They are stored like this:

struct fraction {
    int64_t numerator;
    int64_t denominator;
};

目前,我是这样比较它们的:

Currently, I compare them like this:

bool fraction_le(struct fraction a, struct fraction b)
{
    return a.numerator * b.denominator < b.numerator * a.denominator;
}

效果很好,除了(64 bit value) * (64 bit value) = (128 bit value),这意味着它会溢出离零太远的分子和分母.

That works fine, except that (64 bit value) * (64 bit value) = (128 bit value), which means it will overflow for numerators and denominators that are too far away from zero.

我怎样才能使比较始终有效,即使是对于荒谬的分数?

How can I make the comparison always works, even for absurd fractions?

哦,顺便说一句:分数总是以简化形式存储的,只有分子可以是负数.也许输入约束使某些算法成为可能...

Oh, and by the way: fractions are always stored simplified, and only the numerator can be negative. Maybe that input constraint makes some algorithm possible...

推荐答案

如果你使用 GCC,你可以使用 __int128.

If you are using GCC, you can use __int128.

这篇关于比较两个分数(&lt; 和朋友)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆