简体   繁体   English

c#:添加两个大整数给出错误的结果

[英]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.但是如果在控制台中我将 int 类型的最大值放入,我不会得到异常,但结果是错误的,即使我将结果保存在一个 long 变量中。 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?但是如果 sum 变量很长,为什么我得到错误的结果?

The result is not of type long .结果不是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 .它是int类型,然后它被转换为 long 以将其分配给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.执行上述任一操作,由于一个操作数是 (long) 类型,因此转换后,另一个操作数也将转换为 long,以便将两个值相加并将结果存储到sum变量中。

您必须在很长时间之前将 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 .关键就像已经提到的那样,您需要将其中一个值转换为long才能保留正确的值,否则结果值在分配给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.我想建议您可以在这些数字类型中使用MaxValue以使计算内存友好,如果这是您将其用于计算的地方。 int takes 32 bits and long takes 64 bits. int需要 32 位, long需要 64 位。 If the result of the calculation is still an int then you can save 32 bits of storage till you really need it.如果计算的结果仍然是int那么您可以节省 32 位的存储空间,直到您真正需要它为止。 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.希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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