简体   繁体   中英

Overflow float in Java

import java.lang.*;

import java.math.*;

public class CFloatExample
{

    // --------------------------------------------------------------------------------
    // Name: main
    // Abstract: This is where the program starts.  
    // --------------------------------------------------------------------------------
    public static void main( String astrCommandLine[] )
    {

        // Declare float variables 
    float fltMinimum = 0;
    float fltMaximum = 0;

    // Set to min/max value of float
    fltMinimum = -3.4E38F;
    fltMaximum = 3.4E38F;

    // Print min/max values for float
    System.out.print( "float Data Type------------------------------------------------\n" );
    System.out.print( "\tMinimum: " + fltMinimum + "\n" );
    System.out.print( "\tMaximum: " + fltMaximum + "\n" );
    System.out.print( "\n" );       // Blank line

    // Confirm by subtracting and adding one to int (integer)
    fltMinimum -= 1.0E0F;
    fltMaximum += 1.0E0F;
    System.out.print( "float Confirmation\n" );
    System.out.print( "\tMinimum: " + fltMinimum + "\n" );
    System.out.print( "\tMaximum: " + fltMaximum + "\n" );
    System.out.print( "\n" );       // Blank line
    }
}

I am trying to get the Float variable to overflow but I am not getting that result, above you can see I tried importing some libraries to see if that would cause it to happen, but in the end it just prints the same number before and after I add 1.

For sufficiently large float s, adding 1 won't do anything: they're so large that they get rounded back down to their original value.

To understand this, let's say you're storing a decimal value with 5 decimal digits of precision, and you have 1000000. If you add 1, you would get 1000001, but since you only have five digits of precision, it rounds back to 1000000.

You'll have to add something bigger.

What you can do is test that Math.nextUp(Float.MAX_VALUE) == Float.POSITIVE_INFINITY , which I suspect is what you want to convince yourself of.

Try adding strictfp tp your class's parameter

public strictfp class CFloatExample { //...

strictfp makes the class to always use fixed decimal points for float and double . For more information on that, read http://en.wikipedia.org/wiki/Strictfp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM