Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why math.Ceiling (double a) not return int directly? [duplicate]

Tags:

Possible Duplicate:
Why doesn't Math.Round/Floor/Ceiling return long or int?

msdn defined this method:Returns the smallest integer greater than or equal to the specified double-precision floating-point number.

but in fact,it is

public static double Ceiling (     double a ) 

why not return int directly? what does microsoft think of ?

like image 274
SleeplessKnight Avatar asked Sep 22 '11 08:09

SleeplessKnight


People also ask

Why do Math ceilings have a double return?

The documentation says about the return value: The smallest whole number greater than or equal to a. If a is equal to NaN, NegativeInfinity, or PositiveInfinity, that value is returned. Therefore the return value has to be double since NaN, NegativeInfinity and PositiveInfinity are fields of Double.

Does Math ceil return an integer?

The Math.ceil() function always rounds up and returns the smaller integer greater than or equal to a given number.

Why does Java ceil return double?

ceil() returns the double value that is greater than or equal to the argument and is equal to the nearest mathematical integer. Note: If the argument is Integer, then the result is Integer. If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.

What does Math ceiling do in C#?

The Math. Ceiling() method in C# is used to return the smallest integral value greater than or equal to the specified number.


1 Answers

It's because the range of a double (±5.0 × 10−324 to ±1.7 × 10308) is much greater than the range of an int (-2,147,483,648 to 2,147,483,647). If the return type were int many possible inputs would fail. For example Math.Ceiling might be forced to throw an OverflowException in a checked context, or it might even return an incorrect result in an unchecked context. This is undesirable behaviour.

Also some special values such as NaN and PositiveInfinity can be returned by this method. This is only possible if the return type is double.

If you believe that the result will fit into an int, you can add an explicit cast:

int result = (int)Math.Ceiling(a); 
like image 122
Mark Byers Avatar answered Jan 03 '23 11:01

Mark Byers