Problems with division in C#
How can I ch开发者_JAVA技巧eck if 204 / 5 is greater than 200 / 5? I experienced difficulty when I attempted this, using both floating-point and decimal math.
Using float or decimal will work... but you need to perform the arithmetic in floating point 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 floating point:
decimal x = 204 / 5m;
decimal y = 200 / 5m;
float/double work just as well:
double x = 204d / 5;
double y = 200d / 5;
So, what's going on if you just use 204 / 5? Well, consider this statement:
double x = 204 / 5;
The compiler doesn't use the type of the variable to work out the type of the right hand side. It works out that the right hand side is just an integer, obtained by dividing two integers. The result is then converted into a double
and assigned to x
. The problem is that the arithmetic is done purely with integers whereas you want the conversion to floating point to be performed earlier, so that you can get a floating point result.
Appending a .0
or an f
to any number forces the language to interpret that number as a floating-point decimal:
204
is an integer,204f
is a single-precision floating-point decimal and204.0
is a double-precision floating-point decimal.
Therefore, 204/5
returns an integer 40
and 204.0/5
returns a double-precision float 40.8
.
if (204.0/5 > 200.0/5) {
// stuff
}
Or, you could take the mathematically-simpler route:
if (204 > 200) {
// because you're dividing both of them by 5
}
if ((204.0 / 5.0) > (200.0 / 5.0)) {
//do stuff!
}
The reason is, when you try to calculate 204/5
, it is exactly calculating int 204 divides int 5
, the result is also an int
in C#. You can try 204m/5
, you will get the correct answer.
if (((float)(204) / 5) > ((float)(200) / 5))
{
//Enter code here
}
else
{
//Enter code here
}
精彩评论