除以Random.next总是得出0?

编程入门 行业动态 更新时间:2024-10-24 06:38:55
本文介绍了除以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?

本文发布于:2023-11-30 00:40:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648150.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Random

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!