+ 5
Explain this (Numbers and negatives)
So I was going through old codes and discovered a Fibonacci code that looked similar to this one. After some playing with my code, I realised that the numbers started changing to negatives. I changed the Int to a Long, and what do you now? The negative numbers disappeared... until the last few. I think I know why it's doing so, but can someone please explain to me why it's doing this? https://code.sololearn.com/cN8IUE0WIebx/?ref=app
2 Respostas
+ 10
This has to do with data types and their storage capacities.
int can store 32 bits worth of data. The values that can fit in an int range between -2.1 billion and +2.1 billion (well, specifically +/-2,147,483,648). If you try to store a number higher than +2.1B in a variable, it wraps around into negative values.
long can store 64 bits worth. It ranges between -9.2 quintillion and +9.2 quintillion (or +/-9,223,372,036,854,775,808). The numbers in the sequence will stay within a long's positive range for longer.
+ 1
As you likely know, all native types have a memory limit in bytes. If you go past that, you get an overflow that is sometimes detected as a loss of pressition, resulting in weird negative numbers or in a excepti9n or crash.
Try double for example, that's the biggest in size.