Number of working decimal numbers

I wrote a program in java about floating point, but the result is not accurate; while the same program, written in C, produced the exact result.

Code snippet:

public class One {

public static void main(String...args){

    double i, num=0.0;
    for(i=0;i<10;i++)
    num=num+0.1;
    System.out.println(num);

    }
}

output : 0.999999999999999999

A program in C is as follows

#include<stdio.h>
main()
{

double i,num=0.0;
for(i=0;i<10;i++)
num=num+0.1;

printf("%f",num);

}

Output : 1.00000

What am I doing wrong?

+4
source share
5 answers

C hides the problem without deleting it

, C , - , . , C 6 . . (, num==1), , .

. ,

double i, num=0.0;
for(i=0;i<10;i++)
   num=0.1*i;
   System.out.println(num);

}

. , == , .

, ( ); bigDecimal .

, 10 2.

10 , ; 1/3. , , 1/10.

, "0.1", 10, , 0.1=(binary)0.00011001100110011001100110011001....... , (binary)0.000110011001100 1. (, 1/2) , ( )

1

+5

BigDecimal. - Java ( ).

double i;
BigDecimal num = BigDecimal.ZERO;
for(i=0;i<10;i++)
    num = num.add(new BigDecimal("0.1"));
System.out.println(num);
+2

Java, , . , 0.1 . . , , .

+1

floating. BigDecimal

. ,

    double i, num=0.0;
    for(i=0;i<10;i++) {
        System.out.println(num);
        num=num+0.1;
    }
    System.out.println(num);

Out put

0.0
0.1
0.2
0.30000000000000004 // wrong value, it should be 0.3
0.4
0.5
0.6
0.7
0.7999999999999999 // this one should be 0.7+0.1=0.8
0.8999999999999999 // this should be 0.8+0.1=0.9
0.9999999999999999 // final result should be 0.9+0.1=1

BigDeciaml

 double i;
 BigDecimal num=BigDecimal.ZERO;
 for(i=0;i<10;i++) {
     System.out.println(num);
     num=num.add(new BigDecimal("0.1"));
   }
 System.out.println(num);

Out put

0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
0

strictfp, :

strictfp class Example
{
    //your code here
}

strictfp is a keyword introduced in Java SE 2 (or somewhere near it) as the floating point model relaxed a bit.

0
source

All Articles