tags:

views:

82

answers:

3

I'm doing simple divisions in c#, and I am a bit puzzled by its intricacies. Here's some code, and in the comments, the result. (btw, I only compile with 1 line not commented, if you say that I have 5 declarations of the same variable)

double result = 2 / 3; //gives 0
double result = Convert.ToDouble(2) / Convert.ToDouble(3); // is good
double result = double.Parse(2) / double.Parse(3); // gives me errors
double result = double.Parse(2 / 3); // gives me errors
double result = Convert.ToDouble(2 / 3); // gives 0

MessageBox.Show(result.ToString());

so if you have a bunch of integers you wanna mess with, you have to convert each one to a double. pretty tedious...

+2  A: 

2 / 3 is dividing two integers, which truncates any remainder. You could do:

double result = 2.0 / 3.0;

That will perform double division.

double.Parse is designed to convert a string to a double, not an integer (for that you can cast directly like (double)intVariable or use Convert.ToDouble(intVariable)). If you want to use a constant, simply put your numbers in the format of 2.0 rather than just 2.

Adam Robinson
+1  A: 

The reason the first line returns 0 is that this is standard behaviour for integer division. Many languages truncate remainders, and C# is one of them.

The reason your Double.Parse calls are failing is because parsing is usually applied to strings. Parsing an integer value doesn't really make sense. Just cast to double instead: (double)2.

itowlson
+3  A: 

Integer division discards the remainder. You don't need to use Convert.ToDouble or double.Parse, you can simply write:

double result = 2.0 / 3;

or

double result = (double)2 / 3;

If either one of the operands is a floating-point value then you get floating-point arithmetic instead of integer arithmetic.

To explain each one:

// 2 / 3 = 0 with a remainder of 2; remainder is discarded
double result = 2 / 3;

// 2.0 / 3.0 = 0.6667, as expected
double result = Convert.ToDouble(2) / Convert.ToDouble(3);

// double.Parse takes a string parameter, so this gives a syntax error
double result = double.Parse(2) / double.Parse(3);

// As above, double.Parse takes a string, so syntax error
// This also does integer arithmetic inside the parentheses, so you would still
// have zero as the result anyway.
double result = double.Parse(2 / 3); // gives me errors

// Here, the integer division 2 / 3 is calculated to be 0 (throw away the
// remainder), and *then* converted to a double, so you still get zero.
double result = Convert.ToDouble(2 / 3);

Hope that helps explain it.

Aaronaught
ahh thx a lot guys. I should have known that 2/3 is truncated thus giving 0.... I also learned that .parse is for strings. and, I learned that you can type (double) instead of Convert.ToDouble. thx guys
jello
@Adam Robinson: Whoops, that was a typo. It was supposed to say `(double)2` without the `.0`, to indicate an explicit cast. Hopefully I didn't confuse anyone other than myself there!
Aaronaught