leora
leora

Reputation: 196791

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

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

Why do I see 0 instead of .73?

Upvotes: 6

Views: 1013

Answers (6)

DJ.
DJ.

Reputation: 6784

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

Upvotes: 3

Paul Tomblin
Paul Tomblin

Reputation: 182850

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

The common work-around is to multiply one of the two numbers by 1.0 to make it a floating point type, or just cast it.

Upvotes: 8

Ben McCormack
Ben McCormack

Reputation: 33118

It's important to understand the flow of execution in a line of code. You're correct to assume that setting the right side of the equation equal to double (on the left side) will implicitly convert the solution as a double. However, the flow execution dicates that x/y is evaluated by itself before you even get to the double pct = portion of the code. Thus, since two ints are divided by each other, they will evaluate to an int solution (in this case, rounding towards zero) before being implicitly converted to a double.

As other have noted, you'll need to cast the int variables as doubles so the solution comes out as a double and not as an int.

Upvotes: 2

user217339
user217339

Reputation:

That’s because the type of the left hand operand of the division (x) is of type int, so the return type of x / y is still int. The fact that the destination variable is of type double doesn’t affect the operation. To get the intended result, you first have to cast (convert) x to double, as in:

double pct = (double)x / y;

Upvotes: 1

mmorrisson
mmorrisson

Reputation: 541

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

Upvotes: 2

Brian Ensink
Brian Ensink

Reputation: 11218

Because the division is done with integers then converted to a double. Try this instead:

double pct = (double)x / (double)y;

Upvotes: 34

Related Questions