Integer Inquiry(多个大数的和java语言实现)

One of the first users of BIT’s new supercomputer was Chip Diller. He extended his exploration of
powers of 3 to go from 0 to 333 and he explored taking various sums of those numbers.
“This supercomputer is great,” remarked Chip. “I only wish Timothy were here to see these results.”
(Chip moved to a new apartment, once one became available on the third floor of the Lemon Sky
apartments on Third Street.)
Input
The input will consist of at most 100 lines of text, each of which contains a single VeryLongInteger. Each VeryLongInteger will be 100 or fewer characters in length, and will only contain digits (no
VeryLongInteger will be negative).
The final input line will contain a single zero on a line by itself.
Output
Your program should output the sum of the VeryLongIntegers given in the input.
Sample Input
123456789012345678901234567890
123456789012345678901234567890
123456789012345678901234567890
0
Sample Output
370370367037037036703703703670
题意分析:输入多个大数,直到输入0结束,然后计算多个大数的和
AC代码如下:

import java.math.*;
import java.util.*;
/*在做题提交的时候类的名称必须为Main,不然会编译错误,当然你在编译器
上写的时候类名必须与文件名相同,但在提交的时候必须要把类名改成Main*/
public class Main {
        public static  void main(String[] args){
         Scanner input=new Scanner(System.in);
         //这里跟c语言里的区别就是不能直接让sum=0,这样是不合法的,必须借助new来赋值
         BigInteger sum=new BigInteger("0");  //将sum赋值为0
        while(input.hasNextBigInteger()){//相当于c语言中的!=EOF
            BigInteger a=input.nextBigInteger();//输入一个大数a
            //还有这里的判断a是否等于0也不能像c语言中直接去判断
            if(a.equals(BigInteger.ZERO))//判断a是否等于0
                break;
             //虽然java中也有累加,但是对于BigInteger类型来讲,只能用add来实现两个数的加法   
            sum=sum.add(a);
        }
        System.out.println(sum);
    }
    
}

注意我上面在判断一个大数是否等于0的时候用的是equal来判断,对于输入的是整数这样判断完全没问题,但是如果是小数,这样判断就没什么用了,因为小数在比较的时候不仅要比较值的大小,还要比较位数的多少,例如:Bigdecimal b = new Bigdecimal(“0”) 和 Bigdecimal c = new Bigdecimal(“0.0”),用equals比较,返回就是false。此时b和c的值并不相等,如果想比较的话可以用b.compareTo(BigDecimal.ZERO)==0,可以比较是否等于0,返回true则等于0,返回false,则不等于0

猜你喜欢

转载自blog.csdn.net/weixin_44313771/article/details/106242853