Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

math

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

Why do I see 0 instead of .73?

like image 208
leora Avatar asked Nov 23 '09 20:11

leora


People also ask

Can you divide two ints into a double?

Whatever you try to divide two int into double or float is not gonna happen. But you have tons of methods to make the calculation happen, just cast them into float or double before the calculation will be fine.

What happens when you divide an int by a double in c?

If either operand is a double, you'll get floating point arithmetic. If both operands are ints, you'll get integer arithmetic. 3.5/3 is double/int, so you get a double.

How does c divide integers?

Integer Division and the Remainder Operator For example, the expression 7 / 4 evaluates to 1 and the expression 17 / 5 evaluates to 3. C provides the remainder operator, %, which yields the remainder after integer division. The remainder operator is an integer operator that can be used only with integer operands.


2 Answers

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

double pct = (double)x / (double)y;
like image 172
Brian Ensink Avatar answered Oct 13 '22 21:10

Brian Ensink


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.

like image 44
Paul Tomblin Avatar answered Oct 13 '22 22:10

Paul Tomblin