[英]Adding positive integer to int causes it to become negative
my issue is that when I am adding only positive numbers to an integer it can sometimes become negative. 我的问题是,当我仅将正数添加到整数时,有时会变为负数。 I know that the numbers that are added to the integer are never positive as I have tried putting them in
我知道加到整数上的数字永远不会为正,因为我尝试将它们放入
maths.abs()
My code is below and i would really appreciate some help 我的代码在下面,非常感谢您的帮助
int Total = 0;
int First = 0;
int Second = 10000;
while (First <= Second)
{
Total += 5000 + (250 * First);
Console.WriteLine(Total);
First++;
}
Console.ReadKey();
Please read Checked and Unchecked (C# Reference) . 请阅读Checked和Unchecked(C#参考) 。 You can opt in to bounds checking on arithmetic operations.
您可以选择进行算术运算的边界检查。 EG:
例如:
int Total = 0;
int First = 0;
int Second = 10000;
while (First <= Second)
{
checked
{
Total += 5000 + (250 * First);
}
Console.WriteLine(Total);
First++;
}
Console.ReadKey();
As mentioned by others, your int
can't take that number and overflows. 正如其他人提到的那样,您的
int
无法接受该数字并溢出。 Using an Int64
instead does what you want. 使用
Int64
代替您想要的。
Int64 Total = 0;
int First = 0;
int Second = 10000;
while (First <= Second)
{
Total += 5000 + (250 * First);
Console.WriteLine(Total);
First++;
}
Console.ReadKey();
2,147,483,647 is the limit of the integer, you are adding 1 to the "First" integer each iteration of the loop and overflowing the Total integer 2,147,483,647是整数的极限,在循环的每次迭代中,您都将“ 1”添加到“ First”整数中并溢出Total整数
1 run = 5000 + 0
2 run = 5000 + 5000 + 250
...
10000 run 12,548,750,000
The integer can't hold that and overflows. 整数不能容纳它并溢出。
The limit of a int64 is 9,223,372,036,854,775,807. int64的限制为9,223,372,036,854,775,807。 This would work for your code
这将为您的代码工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.