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

标签 java arrays algorithm

我想使用 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/

相关文章:

java - 从匿名类的角度来看,局部变量遮蔽的字段

java - 通过 JournalStructureLocalServiceUtil Liferay 获取结构名称

java - 如何在启动时调试 Eclipse 崩溃?

c# - 将一维数组显示为行和列

Java - 排序类别

algorithm - 试图理解字符串排列?

java - HttpURLConnection : What is the right way to read data from a WebService, 逐字符还是逐行?

arrays - 将数组划分为子数组,使得子数组不包含重复元素

algorithm - 什么是压缩被阻止文件中记录的好算法?

java - 组合算法并行化