2010-04-01 77 views
0

我正在做简单的分裂在C#中,我有点困惑于它的错综复杂。这里有一些代码,并在评论中,结果。 (顺便说一句,我只用1行编译没有评论,如果你说我有5点声明相同的变量)简单的c#算术。 winForms

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()); 

,所以如果你有一大堆的整数,你想惹的,你必须给每个转换一到两倍。相当乏味...

回答

3

整数除法其余部分。你并不需要使用Convert.ToDoubledouble.Parse,可以简单的写:

double result = 2.0/3; 

double result = (double)2/3; 

如果操作数的任一方为浮点值,那么你得到的浮点运算而不是整数算术。

为了解释每一个:

// 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); 

希望有所帮助解释它。

+0

ahh thx很多家伙。我应该知道2/3被截断,从而给出0 ....我还了解到.parse是用于字符串的。并且,我了解到可以键入(double)而不是Convert.ToDouble。 thx guys – jello 2010-04-01 03:23:15

+0

@亚当罗宾逊:哎呀,那是一个错字。它应该说'(double)2'没有'.0',表示明确的演员。希望我没有把我自己以外的任何人混淆! – Aaronaught 2010-04-01 03:37:33

2

2/3是划分两个整数,它会截断任何余数。你可以这样做:

double result = 2.0/3.0; 

这将执行双重划分。

double.Parse被设计成一个string转换为double,而不是一个整数(对于您可以直接浇铸像(double)intVariable或使用Convert.ToDouble(intVariable))。如果您想使用常数,只需将您的数字格式设置为2.0而不仅仅是2

1

第一行返回0的原因是这是整数除法的标准行为。许多语言截断余数,而C#就是其中之一。

Double.Parse调用失败的原因是因为解析通常应用于字符串。解析一个整数值并不合理。只需投入双倍代替:(double)2