这真的让我感到困惑。我正在编写带有一些随机变化的损伤算法。当我计算变化时,它就是它的样子。
This one is really puzzling me. I am writing a damage algorithm with some random variation. When I calculate the variation this is what it looks like.
Random random = new Random(); Double variation = random.Next(85, 115) / 100; Double damage = restOfAlgorithm * variation;当我这样做时,变化总是输出0。但是,如果我像下面这样操作,它将输出
When I do that, variation always outputs 0. However, if I do like below, it will output the expected result.
Random random = new Random(); Double variation = random.Next(85, 115); Double damage = restOfAlgorithm * (variation / 100);为什么会这样?
推荐答案除以两倍:
Double variation = random.Next(85, 115) / 100.0;或
Double variation = random.Next(85, 115) / (double)100;否则,您将要进行整数运算(因为 Random.Next 返回一个整数,100也是一个整数。)
Otherwise you'll be doing integer arithmetic (since Random.Next returns an integer and 100 is also integer).
我认为最好的方法是知道要使用的类型并将所有类型转换为所需的类型。当然,这超出了必要,因为编译器将隐式转换值。但是使用显式强制转换后,稍后查看代码的人就会看到您的意图。
I consider it best practice to know what types you are working with and cast everything to the type desired. Certainly this is more than is necessary, as the compiler will implicitly convert values. But with explicit casts your intentions are then visible to someone looking at the code later.
Double variation = (double)random.Next(85, 115) / 100d;更多推荐
除以Random.next总是得出0?
发布评论