如何在不使用C#BIGINT加上或减去非常大的数字? [英] How to add or subtract very large numbers without bigint in C#?
问题描述
因此,让我说,我是很少约C#适度知识新手启动
来到正题:我需要一个程序,能够加/减非常大的整数。最初,使用BigInt有才发现它是不允许的。应该有这样一个逻辑的解决方法?我有使用在您添加的每个数字从右到左开始小学法的想法。
我做了,我分成字符数组,并添加一个字符串从右每个数字到左(GetUpperBound-ⅰ)。但它似乎没有工作。
我的代码:
字符串s,S2;
的char [] c_arr,c_arr2;
INT I,尔格;
S =1234;
S2 =5678;
c_arr = s.ToCharArray();
c_arr2 = s2.ToCharArray();
表示(I = 0; I&下; = c_arr.GetUpperBound(0);我++)
{
尔格= c_arr [c_arr.GetUpperBound(0)-i] + c_arr2 [c_arr2。 GetUpperBound(0)-i];
Console.Write图(ERG);
}
Console.ReadKey();
有几件事情错了你的代码小学法。您不占随身携带,你加起来ASCII值而不是实际值0〜9之间,而你输错了顺序的结果。
下面的代码,虽然不是很优雅,不会产生正确的结果:
VAR S1 =1234;
VAR S2 =5678;
无功矣= FALSE;
VAR的结果=的String.Empty;
的for(int i = s1.Length-1; I> = 0;我 - )
{
VAR加数= Convert.ToInt32(s1.Substring(我,1));
变种加数= Convert.ToInt32(s2.Substring(I,1));
无功之和= +加数加数;
总和+ =(携带?1:0);
矣= FALSE;
如果(总和> 9)
{
矣= TRUE;
总和 - = 10;
}
结果= sum.ToString()+结果;
}
如果(进位)
{
结果=1+结果;
}
Console.WriteLine(结果);
So let me start by saying that I'm a newbie with little to moderate knowledge about C#.
Coming to the topic: I need to make a program that is able to add/subtract very large integers. Initially, used BigInt only to find out it's not allowed. There should be a logical workaround for this? I have an idea which is using "elementary school method" where you add each digit starting from right to left.
I made a string which I split into char array and added each digit from right to left(GetUpperBound-i). But it doesn't seem to work.
My Code:
string s, s2;
char[] c_arr, c_arr2;
int i, erg;
s = "1234";
s2 = "5678";
c_arr = s.ToCharArray();
c_arr2 = s2.ToCharArray();
for (i = 0; i <= c_arr.GetUpperBound(0); i++)
{
erg = c_arr[c_arr.GetUpperBound(0)-i]+c_arr2[c_arr2.GetUpperBound(0)-i];
Console.Write(erg);
}
Console.ReadKey();
There are a few things wrong with your code for the 'elementary school method'. You don't account for carry, you're adding up ascii values rather than actual values between 0-9, and you're outputting the results in the wrong order.
The code below, whilst not very elegant, does produce the correct results:
var s1 = "1234";
var s2 = "5678";
var carry = false;
var result = String.Empty;
for(int i = s1.Length-1;i >= 0; i--)
{
var augend = Convert.ToInt32(s1.Substring(i,1));
var addend = Convert.ToInt32(s2.Substring(i,1));
var sum = augend + addend;
sum += (carry ? 1 : 0);
carry = false;
if(sum > 9)
{
carry = true;
sum -= 10;
}
result = sum.ToString() + result;
}
if(carry)
{
result = "1" + result;
}
Console.WriteLine(result);
这篇关于如何在不使用C#BIGINT加上或减去非常大的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!