Domanda

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][1] = 3 <--- is the denominator

Or just 2/3 in this case. 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.

È stato utile?

Soluzione

Cross multiply the two numerators by one another's denominators

IE

2/3 vs 1/50th: multiply 50 and 1 by 3 and multiply 2 and 3 by 50.

Then you can compare the numerator without having to convert to a float.

Altri suggerimenti

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.

i.e. 2*50 = 100; 1 * 3 = 3; ==> 100 > 3

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top