gpt4 book ai didi

java - 按元素对两个数组求和,携带 1 时出现问题

转载 作者:行者123 更新时间:2023-11-30 04:01:00 26 4
gpt4 key购买 nike

所以我已经让这两个数组在不需要携带任何东西时正确添加。所以 a[0,1,1] + b[0,1,1] 会给我 c[0,0,2,2],但如果我类似地做 a[0,9,9] + b[0, 9,9] 我只得到 c[0, 0, 8, 8]。 addBigInts 方法中的循环似乎没有按照我想象的方式工作。任何想法表示赞赏。

import java.util.*;

public class AddBigInts {

public static void main(String[] args) {
Scanner console = new Scanner(System.in);
//init firstNum array
int[] firstNum = new int[getDigit()];
System.out.println("First number:");
//gets input to pop array
firstNum = getInt(firstNum);
//second array is same length
int[] secondNum = new int[firstNum.length];
System.out.println("Second number:");
//pop second array
secondNum = getInt(secondNum);
System.out.println(Arrays.toString(firstNum));
System.out.println(Arrays.toString(secondNum));
addBigInts(firstNum, secondNum);
}

//creates array that is one place bigger than entered #
public static int getDigit (){
Scanner console = new Scanner(System.in);
System.out.print("How many digits? ");
int arraySize = console.nextInt();
return arraySize + 1;
}

//populates array
public static int[] getInt (int[] num){
Scanner console = new Scanner(System.in);
for (int i=num.length-1; i>0; i--){
System.out.print("Digit " + i + ": ");
num[i] = console.nextInt();
}
return num;

}

//adds both arrays by index into the sum array
public static int[] addBigInts (int[]numArray1, int[] numArray2){
int count = Math.max(numArray1.length, numArray2.length);
int[] sum = new int[count+1];
//starting at numArray1 & 2 index, sums ints
for (int i=count-1; i>=0; i--){
//sum has to be +1 for numArray1 & 2 indexes
sum[i+1] = numArray1[i] + numArray2[i];
if (sum[i+1]>9){
//this line below doesn't seem to execute
sum[i]++;
sum[i+1] = sum[i+1] - 10;
}
else;

}
System.out.println(Arrays.toString(sum));
return sum;
}
}

最佳答案

你有:

sum[i+1] = numArray1[i] + numArray2[i];

您需要:

sum[i+1] += numArray1[i] + numArray2[i];

通过赋值而不是相加,您将覆盖前一个数字中的进位 1。

关于java - 按元素对两个数组求和,携带 1 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21974588/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com