程序语言中整数类型的大小都是有限的,在C#中int(System.Int32)的取值范围为:-2,147,483,648 到 2,147,483,647;但如果实际运用中,有一个数大于2,147,483,647或者小于-2,147,483,648,那就可能出错,导致无法运算,下面的程序运用乘法的运算方法,用位数字的叠加来组合形成正确的结果,程序如下(此程序未考虑负数):
using System;
using System.Collections.Generic;
using System.Text;
namespace BigNumber
{
class Program
{
static void Main(string[] args)
{
Console.Write("Number A is : ");
string Aa = Console.ReadLine();
int[] A = new int[Aa.Length];
for (int i = 0; i < Aa.Length; i++)
{
A[Aa.Length-1-i] = Convert.ToInt32(Aa.Substring(i, 1));
//Console.WriteLine(A[Aa.Length - 1 - i]);
}
Console.Write("Number B is : ");
string Bb = Console.ReadLine();
int[] B = new int[Bb.Length];
for (int i = 0; i < Bb.Length; i++)
{
B[Bb.Length-1-i] = Convert.ToInt32(Bb.Substring(i, 1));
//Console.WriteLine(B[Bb.Length - 1 - i]);
}
int[,] sum = new int[Aa.Length,Bb.Length];
int[] wsum = new int[Aa.Length + Bb.Length];
for (int i = 0; i < Aa.Length; i++)
{
for (int j = 0; j < Bb.Length; j++)
{
sum[i,j] = A[i]*B[j];
wsum[i + j] = wsum[i + j] + sum[i, j];
if (wsum[i + j].ToString().Length > 1)
{
wsum[i + j + 1] = wsum[i + j + 1] + wsum[i + j]/10;
wsum[i + j] = Convert.ToInt32(wsum[i + j].ToString().Substring(1, 1));
}
Console.WriteLine("sum[" + i + "," + j + "] = {0}", sum[i, j]);
}
}
string end = "";
for (int m = 0; m < Aa.Length + Bb.Length; m++)
{
Console.WriteLine("wsum[" + m + "] = {0}", wsum[m]);
end = wsum[m].ToString() + end;
}
Console.WriteLine();
Console.WriteLine("================================================================");
Console.WriteLine("计算结果为:{0}",end);
Console.ReadLine();
}
}
}