C # - Int operation inexplicably returning a negative value

The operation is as follows:

public float InfectionPercent() { return (infected + zombies) * 100 / population; } 

values:

 int infected = 20196093 int zombies = 1978138 int population = 32608521 

Return Value -63

Changing 100 to 100f corrects this.


Why does this operation return -63 instead of 63 ?

+4
source share
4 answers
 20196093 + 1978138 = 22174231 22174231 * 100 = 2 217 423 100 

However, Int.MaxValue 2 147 483 647 , so you click the maximum value.

By setting 100 as a float , you force the float to multiply. Valid float values ​​are between -3.4 Γ— 10^38 and +3.4 Γ— 10^38 (which is 340 decillion, i.e. quite a lot), so it is really correct.

+9
source

This is an integer overflow error

2,147,483,647 - maximum integer value C #

20,196,093 + 1,978,138 = 22,174,231

22,174,231 * 100 = 22,174,231 * 100 = 2,217,423,100

(integer overflows to -2,077,544,195 )

-2,077,544,195 / 32,608,521 = -63.71169655318007

Converting to float prevents this problem, because the float does not overflow for a long time, and when it ends, it becomes infinite.

+3
source

The solution to the problem will be to format the multiplication, as with 100f (for the reasons described by Pierre-Luc Pineau). However, if you want the result of an integer to be returned without casting explicitly, create uint variables, since they can only be positive.

 uint infected = 20196093 uint zombies = 1978138 uint population = 32608521 public uint InfectionPercent() { return (infected + zombies) * 100 / population; } //output is 68 (float output is 68.00134) 

It may not be a bottleneck, but if it is a real-time game, you are likely to get better performance because you avoid casting from int to float (of course, it can be micro-optimization depending on how often you call it).

Change As Chris comments correctly, in this case it is better to use long instead of uint .

+1
source

the maximum number that an integer can contain is 2,147,483,647. If your variables are infected and the zombies are integers, they exceed that number because {(infected + zombies) * 100} = 2,217,423,100> 2,147,483,647. Since it maximizes an integer, it goes into negatives. Try turning the infected and zombie variables into floats, or force the float to multiply by making 100 at 100.00.

0
source

Source: https://habr.com/ru/post/1494783/


All Articles