# 除以随机.次数总是会导致0?[英] Dividing by Random.next always results in 0? ### 问题描述

```Random random = new Random();
Double variation = random.Next(85, 115) / 100;
Double damage = restOfAlgorithm * variation;
```

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

```Double variation = (double)random.Next(85, 115) / 100d;
```

## 其他推荐答案

### 问题描述

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?

## 推荐答案

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

## 其他推荐答案

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.

## 其他推荐答案

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.