Write a program that displays a random coordinate in a rectangle. The rectangle is centered at (0, 0) with width 100 and height 200.
Solution:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int x, y;
// x must be from -50 to 50
x = (int)(Math.random() * 101) - 50;
// y must be from -100 to 100
y = (int)(Math.random() * 201) - 100;
System.out.print("(" + x + ", " + y + ")");
}
if we want to generate from -50 to +500 both inclusive? then ?
ReplyDeletesorry
ReplyDeleteif we want to generate from -50 to +50 both inclusive? then ?
here minimum is -48.98 and maximum is 49.99
ReplyDeleteif we want to generate exactly from -50 to +50 then how
Math.random() generates an interval greater than or equal to 0 and less than 1. So we have 0 <= x < 1. Multiplied by 101 => 0 <= 101 * x < 101. Minus 50 => -50 <= x * 101 - 50 < 51, so both -50 and 50 are included in the above formula.
Delete