Question

I want to print a number as an integer if the number doesn't have a remainder.I tried doing this, but it doesn't seem to work:

if(result%10==0)System.out.println(result.intValue());

Then I tried printing:

System.out.println(result%10);

and if result=7.0, it printed out 7.0. So how do I check if the number has a remainder?

Était-ce utile?

La solution

A floating point value is an integer if it equals its truncation:

public boolean isInteger(double x)
{
    return x == (int) x;
}

However, remember that floating-point numbers often have rounding issues that cause strange results. For example, you might be doing some math and end up with a value of (for example) 1.00000000001 when the correct answer without rounding errors is 1. If you pass such a number to isInteger() above, it'll return false. If this is a concern, you need to do a "close enough" check, using a tolerance parameter.

Maybe something like this, although I imagine it could be improved:

// test if x is "closer than epsilon" to an integer
// typical value for epsilon might be, say, 0.000001

public boolean isInteger(double x, double epsilon)
{
    double delta = Math.Abs(x - (int) x);
    delta -= (int) delta;
    return delta < epsilon;
}

Autres conseils

What is the type of result?

If it is a floating point (non-integer) number, then comparing to 0 may not work.

A better equivalent of

(result%10==0)

might be

(result.intValue() % 10 == 0)

        int p = 4;
        int q = 4;
        int result = p + q;
        int rem = 10;

        int val = result % rem;
        if (val == 0 )
        {
            System.out.println(val + "this value has no remainder");
        }
        else if(val < rem)
        {
            System.out.println("given value cannot be devide brcouse its less than the number it going to devide");
        }
        else {

            System.out.println("the remainde of the given value is  = "+ val);
        }`enter code here`
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top