简体   繁体   English

使用整数比较间隔

[英]comparing intervals using integers

First off, I know there are many different easier/reliable ways to perform what I am about to ask, but that is not the point of my question. 首先,我知道执行我将要问的问题有许多不同的简便/可靠方法,但这不是我要问的重点。

I am attempting to compare two sets of integers as if they were fractions. 我试图比较两组整数,就好像它们是分数一样。 What I mean by this is suppose I have a 2d array: 我的意思是假设我有一个二维数组:

int array[2][2];

array[0][0] = 2;
array[0][1] = 3;
array[1][0] = 1;
array[1][1] = 50;

How I want to treat these numbers is that the number in: 我要如何处理这些数字是:

array[0][0] = 2 <--- is the numerator array [0] [0] = 2 <---是分子

array[0][1] = 3 <--- is the denominator array [0] [1] = 3 <---是分母

Or just 2/3 in this case. 或者在这种情况下只有2/3。 What I want to do is then compare the two fractions; 然后,我想比较两个部分。

if(2/3 < 1/50){
  //blah blah blah code here
}

The caveat here is that I can not convert the numbers to floating point numbers to retain their accuracy or create a temporary floating point placeholder. 需要注意的是,我无法将数字转换为浮点数以保持其准确性或创建临时浮点占位符。 Is there any way to compare these using only integer values? 有什么方法可以仅使用整数值比较它们吗?

I also don't know exactly what I should tag for this question, if you think of something let me know and I'll tag it. 我也不清楚我应该为这个问题加上什么标签,如果您认为有什么要让我知道的话,我会予以标记。

Cross multiply the two numerators by one another's denominators 将两个分子的叉数相乘

IE IE

2/3 vs 1/50th: multiply 50 and 1 by 3 and multiply 2 and 3 by 50. 2/3与1/50:将50和1乘以3,然后将2和3乘以50。

Then you can compare the numerator without having to convert to a float. 然后,您可以比较分子,而不必转换为浮点数。

if(array[0][0]*array[1][1])<array[0][1]*array[1][0])
{
    // your code here

}

The most straightforward way is to find the least common multiple, and then convert the numerator. 最直接的方法是找到最小公倍数,然后转换分子。 After that you could compare the numerator as integers. 之后,您可以将分子比较为整数。

ie 2*50 = 100; 即2 * 50 = 100; 1 * 3 = 3; 1 * 3 = 3; ==> 100 > 3 ==> 100> 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM