252分之1= 0在C#中? [英] 1/252 = 0 in c#?

查看:100
本文介绍了252分之1= 0在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一个计算,并在调试时,我发现这一点:

I'm doing a calc and while debugging i found this:

double num = 1/252;

当我调试此,NUM设置为零(0)。是否有一个原因?我想,使其实际计算。

when I debugged this, num is set to zero (0). Is there a reason for this? I'd like to make it the actual calculation.

感谢

推荐答案

是 - 正在的整数的算术执行该计算。试试这个:

Yes - that calculation is being performed in integer arithmetic. Try this:

double num = 1.0 / 252.0;

基本上,被执行的结果被分配给不影响算术运算的变量的类型。将一个整数由另一个结果是整数;如果你想浮要使用浮点运算,你需要做一个操作数或其他浮点类型。这样做,与文字的一种简单的方法是棒.0就结束。另一种方法是使用 D 说明:

double num = 1d / 252d;

请注意,你只有真正需要做的有一个的操作数为它工作浮点值,但是为了清楚在这种情况下,我可能会做两个。

Note that you only really need to make one operand a floating point value for it to work, but for clarity I'd probably do both in this case.

这很容易与当前文字做的,但对于其他前pressions(变量,方法调用等)的结果你需要使用一个转换:

That's easy to do with literals of course, but for other expressions (variables, the results of method calls etc) you'd need to use a cast:

int x = 1;
int y = 252;
double num = (double) x / (double) y;

同样,你只需要投其中之一,所以这将工作太:

Again, you only need to cast one of them, so this would work too:

int x = 1;
int y = 252;
double num = (double) x / y;

请注意,这不是具体到分裂 - 它影响其他的算术运算符太

Note that this isn't specific to division - it affects the other arithmetic operators too.

这篇关于252分之1= 0在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆