简体   繁体   中英

Dividing Math with C#

This has a potentially simple answer but I can't figure it out -

double Result = 1 / 12;

returns 0, while

double Result2 = 24 / 12;

return 2

What's going on and how can I fix it?

Try this:

double Result = 1 / (double)12;

or this:

double Result = 1 / 12D;

In C# (and also in a lot of other languages), integer division returns an integer. By casting one of the operands to double or explicitly declaring a literal double you can force the division expression to return a double and not truncate after the decimal place.

it is doing integer math because the numbers on the right are evaluated as integers.

try 1.0/12 ;

I think you need to cast your values

double Result = (double)1 / (double)12

has something to do with integer based math always returns an integer.....

this will work too

Decimal.Divide(1, 12)

It has a result with higher precision, but a smaller range.

The problem is that 1 and 12 are integers (of type int , not double ). This means the values ignore anything past the decimal point. When you divide 1 by 12, you get 0.083. Since anything past the decimal point is truncated for int , you are left with 0 .

To get expected results, one of your operands needs to be of type double . You can do this by changing 1 to 1.0 or 12 to 12.0 (or both, as long as at least one of the operands is a double ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM