How do you divide integers and get double in C #?

int x = 73; int y = 100; double pct = x/y; 

Why do I see 0 instead of .73?

+6
math c #
source share
6 answers

Because division is done with integers and then converted to double. Try instead:

 double pct = (double)x / (double)y; 
+34
source share

It does the same in all C-like languages. If you separate two integers, the result is an integer. 0.73 is not an integer.

The common goal is to multiply one of the two numbers by 1.0 to make it a floating point type or just toss it.

+8
source share

because the operation is still in int type. Try double pct = (double)x / (double)y;

+3
source share

Integer division discards the fractional part of the result. See: http://mathworld.wolfram.com/IntegerDivision.html

+2
source share

It is important to understand the flow of execution in a line of code. You are right to assume that setting the right side of the equation equal to double (on the left side) will implicitly convert the solution into a double. However, thread execution describes that x / y is evaluated on its own before you even get to the double pct = code. Thus, since the two int are divisible by each other, they will evaluate the int solution (in this case, rounding to zero) before they are implicitly converted to double.

As already noted, you need to specify int variables as double , so that the solution turns out to be double , and not as int .

+2
source share

This is because the type of the left division operand ( x ) is of type int , so the return type of x / y is still int . The fact that the target variable is of type double does not affect the operation. To get the expected result, you first need to convert x to double , as in:

 double pct = (double)x / y; 
+1
source share

All Articles