senline

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

女儿学习OOP的java练习题:

1、题目:

Write a program that prompts the user to enter an integer and prints the value of thefollowing series in 2 decimal places.The series is: 

1/ 2 + 2/3 + 3/4 + ... + i/(i+1)
Note: you can assume that the input integer will always be > 0.Do not use integer division in your calculation.
For example:

 

 

 2、解答

关键是实现两个整数的除数值,比如 4/5。题目要求不让用java 的除号/。我们回想小学列的除法竖式:

(1)我们先实现一个两个整数相除得到整数部分的方法(4/5 = 1)。这个方法使用减法来实现除法,代码如下:

public static int div2( int num1, int num2){
        int result = 0 ;
        while( num1 >= num2){
            num1 -= num2;
            result++;
        }
        return result;
}

(2)然后我们来实现除法

我们根据小学除法竖式的原理,实现一个整数的除法,只考虑正整数,并且可以指定精度;

 1 public static double div( int num1, int num2, int prec ){
 2         int dec_count = 0;
 3 
 4         double result = div2( num1, num2); //得到结果的整数部分
 5         int rem = num1 % num2;
 6         double dec = 0.1;
 7         for(int i =0 ;i < prec+1; i++){
 8            double n1 = rem * 10 ;
 9            result += div2( n1, num2) * dec;
10            rem = num1 % num2;
11            dec *= 0.1;
12         }
13         return result;
14 }

(3)我们实现最总的结果:1/ 2 + 2/3 + 3/4 + ... + i/(i+1)

 1     public static double calculate( int num ) {
2         double result = 0;
 3         for( int i = 1 ; i <= num; i++){
 4             result += div( i, i+1, 3);
 5         }
 6         //System.out.println(BigDecimal.valueOf(result).setScale(2, RoundingMode.HALF_UP));
 7     }

 (4) 输出

 1 public static void main(String[] args) {
 2         Scanner sc1 = new Scanner(System.in);
 3 
 4         System.out.println("Enter a number: ");
 5         int num = sc1.nextInt();
 6         double result = 0;
 7         for( int i = 1 ; i <= num; i++){
 8             result += div( i, i+1, 3);
 9         }
10         System.out.println("The sum of this series is "+ BigDecimal.valueOf(result).setScale(2, RoundingMode.HALF_UP)); 11 }

结果:

Enter a number: 
10
The sum of this series is 7.98

 

posted on 2022-03-12 16:43  森蓝2010  阅读(94)  评论(0编辑  收藏  举报