除以Random.next总是得出0? [英] Dividing by Random.next always results in 0?

查看:95
本文介绍了除以Random.next总是得出0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这真的让我感到困惑。我正在编写带有一些随机变化的损伤算法。当我计算变化时,它就是它的样子。

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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