So far I have this code
int w = (int)((450-150)*random()+150);
This generates a number between 450 and 150... But I have no idea how to make that number a multiple of 10.
Thanks in advance!
So far I have this code
int w = (int)((450-150)*random()+150);
This generates a number between 450 and 150... But I have no idea how to make that number a multiple of 10.
Thanks in advance!
Easy. Just generate random numbers between 15 and 45...then multiply by 10:
int w = ((int)((45 - 15) * random() + 15)) * 10;
Pick a random number between 45 and 15 and multiply it with 10 -
int w = (int)((45-15)*random()+15) * 10;
Just pick a random integer between 15 and 45, then multiply it by 10:
int w = 10*(int)((45-15)*random()+15);
This smells like homework, but I'll bite:
Instead of starting from wide range of random numbers and them limiting the result, consider starting from a narrow range of numbers and expanding the result.
Your code must generate one of about 30 values, right? So try generating a random value between 0 and 30, then transforming that value into the range you need.
(I'd suggest multiplying by 10 and adding 150.)
If, as I suspect, the OP needs an inclusive range on both ends: needs both the numbers 150 and 450, there is a range error on the answers I've seen so far.
Math.random() returns a number between 0.0 (inclusive) and 1.0 (exclusive). If you want a number between 15 and 45 (both inclusive) your range of values is actually (45 - 15 + 1)... ie: a total of 31 values.
The correct code should be:
int w = ( (int)(((45 - 15 + 1) * random()) + 15) ) * 10;
(45 - 15 + 1) * random() = [0.0..30.999999)
[0..31) + 15 = [15.0..45.999999)
(int)[15.0..46.0) = [15..45] - integer conversion is a truncation, not a rounding
[15..45] * 10 = {150, 160, 170, 180, ..., 440, 450}