简体   繁体   中英

c#: adding two big integers gives wrong result

So I have a code that adds two integers and prints the result:

        Console.WriteLine("enter number: ");
        int intTemp = Convert.ToInt32(Console.ReadLine());
        long sum = intTemp + 5;
        Console.WriteLine($"sum is : {sum}");

But if in the console I will put the maximum value for the int type, I won't get an exception, but the result is wrong, even if I am saving the result in a long variable. Here is the output:

enter number:
2147483647
sum is : -2147483644

But if the sum variable is a long, why I am getting the wrong result?

The result is not of type long . It is of type int and afterwards it is converted to a long in order to assign it to a variable of type long .

That is needed to do, it is the following:

long sum = (long)intTemp + 5;

or

long sum = intTemp + (long)5;

Doing either of the above, since the one operand is of type (long), after conversion, the other would be converted also to long, in order the two values to can be added and the result would be stored to the sum variable.

您必须在很长时间之前将 int "intTemp" 转换为 long,因为只有在计算完成后才将总和转换为 long

The key is like already mentioned that you need to convert one of the values to long to be able to retain the correct value as otherwise the result value is already corrupted before it is assigned to long . I would like to suggest that you can use MaxValue in these numeric types to make the calculation memory friendly if that is where you will use it for calculations. int takes 32 bits and long takes 64 bits. If the result of the calculation is still an int then you can save 32 bits of storage till you really need it. In your example you could do

if (int.MaxValue - 5) < intTemp ) // it means the value will go above int range if add 5
{
  // Make conversion to target type before the operation
}else{ 
  // the value will still be in int range
}

You can use the appropriate storage type for the result then. It can become quite memory efficient if you are storing large number of results and then using them for further calculations. Hope it helps.

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