繁体   English   中英

使用Java中的数组添加两个10位数字

[英]Add two 10-digit numbers using arrays in Java

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

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

额外

您可以走得更远,使进位计算更简单(仅因为我们只添加两位数。在这种假设下,“加法器循环”变为:

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;
  }
}

处理此类问题时,我们需要牢记随身携带的物品。

为了解决这个问题,我们应该从数组的右边开始添加到左边,就像我们在maths类中添加两个数字一样。

我们需要保持随身携带的轨迹。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM