-1

The program I am writing for my class requires a row that counts by 0.1 from 0.5 to 42.9 along with a few other rows. Since doubles are not exact the program counts by 0.1 until 0.7 then the next number becomes 0.799999999 rather than 8. I am a little iffy on the code that corrects this. I want to say it has something to do with Math.abs and EPS but i'm not sure. Any advice would be appreciated.

{
    System.out.println(" ");

    final double MAX2 = 43;

      for (double row = 0.5; row<MAX2; row+=0.1)
    {

      System.out.print(row);
      if(row != MAX2 -1)
      {System.out.print(",");

      }//SOP COMMA
    }//SOP ROW3
  }//.5,42.9

the end result is

0.5,0.6,0.7,0.7999999999999999,0.8999999999999999,0.9999999999999999,1.0999999999999999,1.2,1.3,1.4000000000000001,1.5000000000000002,1.6000000000000003,1.7000000000000004,1.8000000000000005,1.9000000000000006,2.0000000000000004,2.1000000000000005,2.2000000000000006,2.3000000000000007,2.400000000000001,2.500000000000001,2.600000000000001,2.700000000000001,2.800000000000001,2.9000000000000012 etc.

user2805461
  • 1
  • 1
  • 4

2 Answers2

0

A simple way would be to just print the variable out to 1 decimal place using printf.

public static void main(String[] args) {
    System.out.println(" ");

    final double MAX2 = 43;

    for (double row = 0.5; row<MAX2; row+=0.1) {
        System.out.printf("%.1f", row);
        if(row != MAX2 -1) {
            System.out.print(",");
        }
    }
}
0

This is an iteration problem It has nothing to do with doubles whatsoever.

You need a for loop that goes from 5 to 429. Inside the loop, calculate a double value by dividing the loop index by 10. Then use that double value for whatever computation you have in the loop.

Don't forget to cast the index to double before dividing otherwise you will get integer division which does not produce the result that you require.

Michael Dillon
  • 31,973
  • 6
  • 70
  • 106