What is the best practice to do a double return in C #

In C #, when you want to split the result of a method like below, what is the best way to make it return a double value, not a default integer.

(int)Math.Ceiling((double)(System.DateTime.DaysInMonth(2009, 1) / 7));

As you can see, I need the division by the return of the double, so I can use the ceiling function.

+5
source share
6 answers

Separating two numbers intreturns inttruncating any decimal points. This is usually true for other data types: arithmetic operations do not change the type of their operands.

, . double: , # .

: . , , .

, ( d double) . . :

(int)Math.Ceiling(System.DateTime.DaysInMonth(2009, 1) / 7.0);

, a double. float, : 7f.

, . : VB, a double. (\), . ++ : - ptrdiff_t. , , , . , unsigned int a signed int.

+18

7 double:

(int) Math.Ceiling(System.DateTime.DaysInMonth(2009, 1) / 7.0);
+12

:

(int)Math.Ceiling((System.DateTime.DaysInMonth(2009, 1) / 7.0))
+3

, , . double, .

+1

To expand Conrad's answer ...

Changing 7-7.0, 7-7D, 7-7M, you will also get the answer you want.

+1
source

For a completely different approach that allows you to completely eliminate casting and floating point math ...

int result = val1 / val2;
if (val1 % val2 != 0) result++;

So in your case ...

int numDaysInMonth = System.DateTime.DaysInMonth(2009, 1);
int numWeeksInMonth = numDaysInMonth / 7;
if (numDaysInMonth % numWeeksInMonth != 0) numWeeksInMonth++;

This approach is rather verbose, but there may be some special cases where this is preferable. Technically, there should be a slight performance advantage for a modular approach, but it will be difficult for you to measure it.

In your case, I would stick to the accepted answer :-)

0
source

All Articles