Reputation: 19
I wrote this code but sometimes the same input doesn't give me the same output. For example, input 128 or 97.
My C# code is:
age = int.Parse(Console.ReadLine());
double result1 = age *3.156e7;
int result2 = age * 31560000;
Upvotes: 1
Views: 395
Reputation: 1915
int
max value is 2,147,483,647 and 128 * 31560000 = 4,039,680,000 which is greater than int max value, and you will get an Integer overflow
But also age * 31560000 output an int
which his max value is also as above
It doesn't matter if you do
int = age * 31560000
or
long = age * 31560000
(here you expect to get the result as you think but you will get still get an overflow because the compiler first compute the multiple results and then insert it into the result)
to solve this you can do something like this
long result2 = age * Convert.ToInt64(31560000);
because the compiler looks here for higher format and act according to it
Upvotes: 6