Float 0-1 to int 0-17 release

I got this seemingly simple task in a computer class, which turned out to be more complicated than me: the program gets a random floating-point value between 0 - 1, and then I need to turn into an int between 0 - 17, not including 0 and 17 ( sixteen possible values). so I started with a simple loop that didn't actually work, so I went and hard-coded it:

public static float step(float input){
    if(input < (1/16 * 1)){
        return 1;
    }else if(input < (1/16 * 2)){
        return 2;
    }else if(input < (1/16 * 3)){
        return 3;
    }else if(input < (1/16 * 4)){
        return 4;
    }else if(input < (1/16 * 5)){
        return 5;
    }else if(input < (1/16 * 6)){
        return 6;
    }else if(input < (1/16 * 7)){
        return 7;
    }else if(input < (1/16 * 8)){
        return 8;
    }else if(input < (1/16 * 9)){
        return 9;
    }else if(input < (1/16 * 10)){
        return 10;
    }else if(input < (1/16 * 11)){
        return 11;
    }else if(input < (1/16 * 12)){
        return 12;
    }else if(input < (1/16 * 13)){
        return 13;
    }else if(input < (1/16 * 14)){
        return 14;
    }else if(input < (1/16 * 15)){
        return 15;
    }else{
        return 16;
    }
}

but for some reason I just can't find it always 16! Can anyone help me? (JAVA please)

+4
source share
6 answers

Using the mapping function can help you write less code;)

public static float map(float value, float smallestValue, float largestValue, float smallestReturn, float largestReturn) {
    return smallestReturn + (largestReturn - smallestReturn) * ((value - smallestValue) / (largestValue - smallestValue));
}

→ 0 1 . , value = 0, value = 1 : 1 16.

(int) map( randomGeneratedNumber , 0 , 1 , 1 , 16 );

, !

+1

, , , 1/16, , , 0. , 0. , 1.0/16, 1d/16, 1f/16 float, 1d double.

+6

№1:1/16 - .

# 2: ?? , ? (, if....)

+6

The result of integer division is always integer. Change one or both to double (or float) and you will go well.

As an example:

System.out.println("1/16: " + (1/16));
System.out.println("1.0/16: " + (1.0/16));
System.out.println("1/16.0: " + (1/16.0));
System.out.println("1.0/16.0: " + (1.0/16.0));

Runnable version for the lazy: http://ideone.com/jecgGP

+3
source

A problem with

(1/16 * 1)//result is int zero

using

 ((float)1/16 * 1)
+2
source
float  max = 16;
max = max / randomClamped;
int retval = (int)max % 17;
0
source

Source: https://habr.com/ru/post/1609481/


All Articles