gpt4 book ai didi

java - 在 Java 中使用数组添加两个 10 位数字

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:57 25 4
gpt4 key购买 nike

我想使用 3 个数组将两个 10 位数字相加。我写了这些行:

import java.util.*;

public class addition {
public static void main(String[] args){
Scanner enter = new Scanner(System.in);
int[] arr1= new int[10];
int[] arr2 = new int[10];
int [] result = new int [11];

System.out.print("Enter the first array: ");
for(int i=0; i<10; i++)
{
arr1[i]=enter.nextInt();
}
System.out.print("Enter the second array: ");
for(int i=0; i<10; i++)
{
arr2[i]=enter.nextInt();
}

for(int i=0; i<10; i++)
{
int b;
int c;
int a = arr1[9-i]+ arr2[9-i];
if(a>9){
b = a%10;
c = a/10;
result[9-i] = b;
result[10-i] += c;
}
result[9-i]=a;
}
System.out.print("Result: ");
for(int i=10; i>=0; i--)
{
System.out.print(result[i]);
}
}
}

但是程序不能正常运行。结果不正确。

控制台:

Enter the first array: 8
6
9
5
3
9
9
1
4
2
Enter the second array: 8
5
3
8
0
0
3
1
6
6

结果:09103129414131216

我该怎么办?

最佳答案

有两件事需要解决:

  1. 您将数组从后往前填充,这使得输入有悖常理。换句话说这个循环:

    for(int i=0; i<10; i++) {
    arr1[i]=enter.nextInt();
    }

    应该变成:

    for(int i=9; i>=0; i--) {
    arr1[i]=enter.nextInt();
    }

    arr2 也是如此。

  2. 检查进位的主要if语句应该变成:

    if(a>9){
    b=a%10;
    c=a/10;
    result[9-i]=b;
    result[10-i]+=c;
    } else {
    result[9-i]=a;
    }

通过这些修复,您的代码可以正常工作。

额外的

您可以更进一步,让您的进位计算更简单(只是因为我们只添加 2 位数字。在这样的假设下,“加法器循环”变为:

for(int i=0; i<10; i++) {
int a = arr1[9-i] + arr2[9-i];
if (a>9) {
result[9-i] = a-10;
result[10-i] += 1;
} else {
result[9-i] = a;
}
}

关于java - 在 Java 中使用数组添加两个 10 位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47451782/

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