Problems with dividing in C #

How can I check if 204/5 is greater than 200/5? I had difficulty trying this using math with floating point and decimal table.

+5
source share
5 answers

Using float or decimal will work ... but you need to do the floating point arithmetic by making at least one of the operands decimal / float / double:

decimal x = ((decimal) 204) / 5;
decimal y = ((decimal) 200) / 5;

if (x > y) // Yes!

Or use floating point literals:

decimal x = 204m / 5;
decimal y = 200m / 5;

It doesn't matter which operand is a floating point:

decimal x = 204 / 5m;
decimal y = 200 / 5m;

float / double also works:

double x = 204d / 5;
double y = 200d / 5;

So what happens if you just use 204/5? Well, consider this statement:

double x = 204 / 5;

. , , . double x. , , , , .

+15

.0 f :

  • 204 - ,

  • 204f -

  • 204.0 .

, 204/5 40 204.0/5 float 40.8.

if (204.0/5 > 200.0/5) {
    // stuff
}

:

if (204 > 200) {
    // because you're dividing both of them by 5
}
+5
if ((204.0 / 5.0) > (200.0 / 5.0)) {
    //do stuff!
}
0

The reason is that when you try to calculate 204/5, it accurately calculates int 204 divides int 5, the result is also intin C #. You can try 204m/5, you will get the right answer.

0
source
if (((float)(204) / 5) > ((float)(200) / 5))
{
//Enter code here
}
else
{
//Enter code here
}
0
source

All Articles