首页 > 代码库 > 关于大数相乘 溢出的问题

关于大数相乘 溢出的问题

今天在开发过程中遇到很奇怪的问题,几个正整数相乘竟然出现了负数,

debug的提示是 checked模式下,整型溢出

原来是数据相乘后超过了int32的数据范围。

在网上看了一下解决方案

转自:http://www.cnblogs.com/Alpha-Fly/archive/2012/04/02/2429756.html

 一 加载system.Numerics 类库

1 BigInteger num1 = BigInteger.Parse("乘数一");
2 BigInteger num2 = BigInteger.Parse("乘数二");
3 Console.WriteLine(num1* num2);
4 Console.ReadKey();

 

二 

static string getbackresult(string s1, string s2)
            {
                string lastResult = "";
                int ten1 = -1;
                int[] result = new int[s1.Length + s2.Length];//用以记录计算结果
                for (int i = s1.Length - 1; i >=0; i--)
                {
                    int c1 = Convert.ToInt16(s1[i].ToString());//从s1中从后往a前取一个数并记录这个数的位置
                    ten1++;
                    int resultindex = result.Length - 1 - ten1;
                    for (int j = s2.Length - 1; j >=0; j--)
                    {
                        int c2 = Convert.ToInt16(s2[j].ToString());//从?s2中从后往前取一个数
                        int cc = c1 * c2 + result[resultindex];
                        if (cc > 10)
                        {
                            result[resultindex] = cc % 10;
                            int lastindex = resultindex - 1;  //往前移动一位
                            int lastvalue = http://www.mamicode.com/result[lastindex] + cc / 10; //把刚刚得到的十位的数字赋值到前面
                            while (cc > 10)
                            {
                                cc = result[lastindex] + cc / 10;
                                result[lastindex] = cc % 10;
                                lastindex--;//进位
                            }
                        }
                        else
                        {
                            result[resultindex] = cc;
                        }
                        resultindex--;//进位
                    }
                }
                StringBuilder sb = new StringBuilder();
                foreach (int item in result)
                {
                    sb.Append(item);
                }
                lastResult = sb.ToString();
                if (lastResult[0]==‘0‘)
                {
                    lastResult = lastResult.Substring(1);
                }
                return lastResult;
            }

关于大数相乘 溢出的问题