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 co开发者_开发知识库nvert each one to a double. pretty tedious...
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.
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
.
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
.
精彩评论