Typical interview questions: 0.01 + 0.02 + 0.03 +... + 1.0 =? Is 50.5.
The first incorrect idea: package 3_exercise question; // calculate 0.01 + 0.02 + 0.03 + ...... + 1.0 =? Public class Test8 {public static void main (String [] args) {double sum = 0.0; for (double d = 0.01; d <= 1.0; d = d + 0.01) {sum = sum + d;} System. out. println ("sum obtained by the for loop of the double type and \ nsum =" + sum );}}Sum obtained by the for loop of the double Type
Sums = 49.50000000000003
The second is incorrect:
Package 3_exercise question; // calculate 0.01 + 0.02 + 0.03 + ...... + 1.0 =? Public class Test8 {public static void main (String [] args) {double sum = 0.0; float sum2 = 0.0f; // note that f must be added, because the default value is double type, it is not as strong as float ). For (float d = 0.01f; d <= 1.0f; d = d + 0.01f) {sum = sum + d;} System. out. println ("sum obtained by the float type for the for Loop and \ nsum =" + sum);} sum obtained by the float type for the loop and sum = 50.499976608902216The third is the correct idea.
Package 3_exercise question; // calculate 0.01 + 0.02 + 0.03 + ...... + 1.0 =? Public class Test8 {public static void main (String [] args) {double sum = 0.0; double d = 0.01; double newSum = 0.0; for (int I = 0; I <100; I ++) {sum = sum + d; newSum = (int) (sum * 100.0)/100.0; d = d + 0.01;} System. out. println (newSum );}}
The correct answer is 50.5