topic:
1/1 + 1/2 + 1/3 + 1/4 + ... is mathematically called a harmonic series.
It is diverging, that is, by adding enough terms, you can get arbitrarily large numbers.However, it diverges very slowly: the sum of the
first 1 item and the first 4 items reaches 1.0
and the sum of the first 83 items exceeds 2.0
, and the sum of the first 83 items exceeds 5.0
. Please calculate, how many items must be added to make the sum reach or exceed 15.0?
Please fill in this integer.
Note: Only need to fill in an integer, do not fill in any redundant content. Such as description text.
Answer:
//1835421
import java.util.Scanner; public class Main{ public static void main(String[] args){ double sum=0; double i=0; while(true){ i++; sum+=1/i; // if(sum>2){ // System.out.println((int)i); // return; // } // if(sum>5){ // System.out.println((int)i); // return; // } if(sum>=15){ System.out.println((int)i); return; } } } }
Analysis: First calculate the data as a decimal, so all variables involved in the calculation need to use double type, and use the two test data in the question to analyze the correctness of the code.
Summary: When calculating, try to ensure the same precision of variables as possible, otherwise errors are prone to occur.