简体   繁体   中英

Why do I not get the correct result when multiplying extremely large numbers?

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM