What you're seeing is caused by floating point inaccuracy. You must be careful when going between floating points and integers and when printing floating points.
Since floating points cannot represent all numbers exactly, it often attempts to get as close as possible. What is likely happening is that instead of 16, totalMemory
is something like 15.999999999987
and then when this gets converted to an int, it gets truncated to 15.
There are two ways you can fix this: if you know totalMemory
is divisible by 1024*1024
, then just use integers (this would not work in the case of non integer gigabytes). Since you're using an integer anyway, you might as well use this approach. (768MB cannot be expressed as an integral amount of GB).
The other option is to add in an epsilon to prevent this. In other words, instead of using totalMemory
, you would use something like totalMemory + 1e-7
. The epsilon is too insignificant to make a meaningful difference, but it can push something like 15.999...
up to 16
.
By the way, floating point problems are only part of your problem. If you're going to use an integer, you probably want to use MB instead of GB. How can an integer represent something like 4.5GB (although that's very rare these days)?