Dividing by Random.next always results in 0?

风格不统一 提交于 2019-12-12 02:27:08

问题


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;

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

Why does this happen?


回答1:


Divide by a double:

Double variation = random.Next(85, 115) / 100.0;

or

Double variation = random.Next(85, 115) / (double)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;



回答2:


Because random.Next will give you an integer and 100 is also an integer. So dividing them will either result in 0 or 1 depending if your random number if below or above 100. You need to divide by 100.0 in order to get a double division.




回答3:


The method random.Next(lower_bound, upper_bound) returns an integer value (int type). In the first case you have random.Next(85, 115) / 100 and this is a division of int variables. In C# it implies integer division (when both numbers and ints). That is why it sometimes returns 0.
In the second case you use variation which is of type double. That is why C# converts the result to double and then everything is OK.




回答4:


As everyone else Mentioned: random.Next() will return an integer.

Instead use: random.NextDouble(), this will give you a nice double to calculate with, as it returns a double between 0 and 1 that you can process further to fit your range.

double variation = random.NextDouble() * range + minimum;

alternatively you can divide by double as mentioned in the other answers:

double variation = random.Next(minimum, minimum + range) / 1.0 /*or*/ (double)1


来源:https://stackoverflow.com/questions/18991093/dividing-by-random-next-always-results-in-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!