Typical interview questions: 0.01 + 0.02 + 0.03 +... + 1.0 =? Is 50.5.

Source: Internet
Author: User

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.499976608902216
The 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.