浏览 1743 次
锁定老帖子 主题:java大正数的乘法,但显示数组越位。
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2011-04-17
最后修改:2011-04-17
public class new1{ //将输入进来的字符串转换为int数组。 public static int[] returnArray(String Big){ int Biglength = Big.length(); int [] Array = new int[Biglength]; for(int i = 0 ;i <=Biglength - 1;i++){ Array[i] = Integer.parseInt(Big.substring(i,i+1)); } return Array; }// public static String chengfa(String first,String second) { int longfirst = first.length(); int longsecond = second.length(); int longfs = longfirst+longsecond; int [] Intfirst = returnArray(first); int [] Intsecond = returnArray(second); int [][] result = new int[longsecond][longfs]; //用来存两个数相乘的结果。 int [] addresult = new int[longfs]; //用来存result数组中同列不同行的数据相加的值。 String endresult=""; int add = 0; //初始化result数组的值为零 for(int i=0; i<=longsecond-1;i++){ for(int j=0;j<=longfs-1;j++){ result[i][j]=0; } }// //将first和second 两数相乘的值存放到数组result中。 for(int i=longsecond-1;i>=0;i--){ for(int j=longfirst-1;j>=0;j--){ result[longsecond-i-1][j+i-1]=Intfirst[j]*Intsecond[i]; } }// //将result数组中同列不同行的各个数相加。 for(int i=longfs-1;i>=0;i--){ for(int j=0;j<longsecond-1;j++ ){ addresult[i] += result[j][i]; } }// //将addresult数组中个元素进行相加,进位,得出为字符串的结果。 for(int i=longfs-1;i>=0;i--){ int a = (addresult[i]+add)%10; //得出各个余数。 int b = (addresult[i]+add)/10; //得出各个商的值。 //判断b的值,并重新给add赋值。 endresult += a; if(b>0){ add=b; }// } return endresult; } public static void main(String args[]) { System.out.println(chengfa("44121","34633")); } } Myeclipse运行的结果如下: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at new1.chengfa(new1.java:47) at new1.main(new1.java:80) 麻烦各位看一下,不胜感激。 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2011-04-24
最后修改:2011-04-24
//将first和second 两数相乘的值存放到数组result中。 for(int i=longsecond-1;i>=0;i--){ for(int j=longfirst-1;j>=0;j--){ result[longsecond-i-1][j+i-1]=Intfirst[j]*Intsecond[i]; } }// result[longsecond-i-1][j+i-1]这句 应该是i+j+1 循环初值i,j分别减过1,使得i+j-1只有7了,实际数组下标是longfirst+longsecond-1 = 9 for(int i=longfs-1;i>=0;i--){ for(int j=0;j<longsecond-1;j++ ){ addresult[i] += result[j][i]; } }//这里for(int j=0;j<longsecond-1;j++ ) 这里判断条件应为j<=longsecond-1 //判断b的值,并重新给add赋值。 endresult += a;这里字符串最后输出是反的。。比如123,实际输出变成了321 可以考虑初始化 char[] endresult = new char[longfirst+longsecond], //判断b的值,并重新给add赋值。 endresult[i] = (char) ('0'+a); if(b>0){ add=b; }// } return new String(endresult); over,lz共同进步 |
|
返回顶楼 | |