go to previous page   go to home page   go to next page hear noise highlighting

Answer:

double value ;
int tenths  = 0;
int inc     = 1;           // each "1" represents one tenth
 
while ( tenths  <= 100 )   // 100 tenths is 10.0
{
  value  = tenths/10.0 ;      // be sure to divide by a double 10.0
  System.out.println( "value:" + value );
  tenths =  tenths + inc ;
}
System.out.println( "done");

Use Integers for Counting

You might want a double or float for the loop control variable. You would add 0.1 to it each iteration. This would nearly work, but leads to errors. The value 0.1 cannot be accurately represented in binary. A loop that repeatedly adds 0.1 to a variable will accumulate errors.

Just for fun, here is a program fragment that does just that. Enter various limit amounts and see how much error there is:


// enter a value for limit
float inc   = 0.1 ;
float value = 0.0 ;

float limit =  ;

while ( value < limit )  // notice "less-than" operator
{
  value = value + inc;
}
System.out.println( "Value was " + value + " when the loop ended");



Enter the limit value :    

Although the above program is implemented in JavaScript running in your web browser, the same problem will occur with Java.


QUESTION 13:

If you enter a limit of 10.0, what would be printed out if the arithmetic were perfectly accurate?


go to previous page   go to home page   go to next page