0

I am trying to add a value 1.12 between the Min and Max values

Min = 1.3
Max = 6.9

ie

1.3 + 1.12 = 2.42
2.42 + 1.12 = 3.54

till it reaches max value.

What I did is

double sum = 0,BucWidth = 1.12; 
sum = min + BucWidth ;
while(sum != max){
    sum = sum +BucWidth ;
    System.out.println("SUmmmmm" + sum);
}

But it is not stopping when sum reaches max.

Am I doing anything wrong.

Pls Suggest

3 Answers 3

7
while (sum <= max) {
  sum = sum + BucWidth;   // or sum += bucWidth;
  System.out.println("SUmmmmm" + sum);
}

You should check if it is less than or equal to, not if it is not equal to in your while condition, since you want to exit the loop when it reaches the limit.

Sign up to request clarification or add additional context in comments.

2 Comments

As a side note, recommend to follow Java naming conventions: bucWidth instead of BucWidth
@UnmeshaSreeVeni: the reason you need to do this is because floating point numbers can not be represented with 100% accuracy on digital computers. While 1.3 + 5 * 1.12 should == 6.9, it won't == exactly, but rather will be very very close.
4

In general, comparing floating-point numbers for exact equality is asking for trouble unless you have a deep understanding of exactly where and when roundoff will occur. It's safer to use < rather than !=, since the value may never exactly match the one you're expecting.

(This annoyance is one of many reasons that programming languages have int and float as separate datatypes.)

Comments

0

For floating point numbers or long double types it might happen that doing mathematical operations like adding a value to another value might not be equal to a value you assumed as in integer addition operations.

int a=6;
while(sum!=12)
{
sum+=sum;
}

This iterates once.

Consider this

  double a=7.4564;
    double b=7.4567;
            if(a==b){
                System.out.println("Both are equal");
            }
    else{
    System.out.println("Both are unequal");
    }

Output:-Both are unequal

This is because some number after the decimal can change and so when operations like != are used the numbers have to be exact in all decimal places as used or else the logic won't work. So it is better in your case to use <= instead of != while comparing sum and max.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.