Java/๋ฌธ๋ฒ•

[Java ๋ฌธ๋ฒ• ์ด์ •๋ฆฌ] Math ํด๋ž˜์Šค, Random ํด๋ž˜์Šค

soowitty 2024. 1. 27. 01:11
๐Ÿ’ก ๋Œ€๋ถ€๋ถ„์˜ ๋‚ด์šฉ์„ ์ ํ”„ ํˆฌ ์ž๋ฐ” ์—์„œ ์ฐธ๊ณ ํ•˜์—ฌ ์ •๋ฆฌํ•˜์˜€์Šต๋‹ˆ๋‹ค.

 

Math ํด๋ž˜์Šค

Math ํด๋ž˜์Šค๋Š” java.Lang ํŒจํ‚ค์ง€์— ํฌํ•จ๋œ ํด๋ž˜์Šค๋กœ ์ˆ˜ํ•™๊ณผ ๊ด€๋ จ๋œ ์ผ๋ จ์˜ ์ž‘์—…๋“ค์„ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค. Math ํด๋ž˜์Šค์˜ ๋‹ค์–‘ํ•œ ๋ฉ”์†Œ๋“œ๋“ค์€ ์ „๋ถ€ static์œผ๋กœ ๊ตฌํ˜„๋˜์–ด ์žˆ์œผ๋ฏ€๋กœ ๋”ฐ๋กœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜์ง€ ์•Š๊ณ  ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

System.out.println(Math.max(10,50)); // 50 ์ถœ๋ ฅ
System.out.println(Math.min(10,50)); // 10 ์ถœ๋ ฅ
System.out.println(Math.abs(-10));   // 10 ์ถœ๋ ฅ
System.out.println(Math.random());   // 0.0 ~1.0 ์‚ฌ์ด์˜ ๋‚œ์ˆ˜ ์ถœ๋ ฅ

 

๋ฉ”์†Œ๋“œ

max(), min()

  • ์ž…๋ ฅํ•œ ๋‘ ๋ฐ์ดํ„ฐ ์ค‘ ๋” ํฐ ์ˆ˜์™€ ๋” ์ž‘์€ ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜

abs()

  • ์ž…๋ ฅํ•œ ๋ฐ์ดํ„ฐ์˜ ์ ˆ๋Œ€๊ฐ’์„ ๋ฐ˜ํ™˜

random()

  • 0.0~1.0 ์‚ฌ์ด์˜ ์ž„์˜์˜ doubleํ˜• ๋ฐ์ดํ„ฐ๋ฅผ ์ƒ์„ฑํ•˜์—ฌ ๋ฐ˜ํ™˜
  • ์ด ๋ฉ”์†Œ๋“œ๋ฅผ ํ†ตํ•ด ํŠน์ • ๋ฒ”์œ„์˜ ๋‚œ์ˆ˜ ๋ฐœ์ƒ ๊ฐ€๋Šฅ
System.out.println((int)(Math.random() * 10));   // 0~9 ์‚ฌ์ด ๋‚œ์ˆ˜ ๋ฐœ์ƒ
System.out.println((int)(Math.random() * 100));  // 0~99 ์‚ฌ์ด ๋‚œ์ˆ˜ ๋ฐœ์ƒ   
System.out.println((int)(Math.random() * 1000)); // 0~999 ์‚ฌ์ด ๋‚œ์ˆ˜ ๋ฐœ์ƒ

 

Random ํด๋ž˜์Šค

Random ํด๋ž˜์Šค๋Š” java.Lang ํŒจํ‚ค์ง€์— ํฌํ•จ๋œ ํด๋ž˜์Šค๋กœ, ๋‚œ์ˆ˜๋ฅผ ์ƒ์„ฑํ•ด์ค€๋‹ค.

Math ํด๋ž˜์Šค์™€ ๋‹ค๋ฅด๊ฒŒ ๊ฐ์ฒด๋ฅผ ์žฌํ™œ์šฉํ•˜์—ฌ ์ง€์†์ ์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

๋ฉ”์†Œ๋“œ

boolean nextBoolean() booleanํ˜• ๋‚œ์ˆ˜ ๋ฐ˜ํ™˜
int nextInt() intํ˜• ๋‚œ์ˆ˜ ๋ฐ˜ํ™˜
long nextLong() longํ˜• ๋‚œ์ˆ˜ ๋ฐ˜ํ™˜
int nextInt(int n) 0์ด์ƒ n๋ฏธ๋งŒ์˜ ๋ฒ”์œ„๋‚ด์— ์žˆ๋Š” intํ˜• ๋‚œ์ˆ˜ ๋ฐ˜ํ™˜
float nextFloat() 0,0์ด์ƒ 1.0๋ฏธ๋งŒ์˜ floatํ˜• ๋‚œ์ˆ˜ ๋ฐ˜ํ™˜
double nextDouble() 0.0์ด์ƒ 1.0๋ฏธ๋งŒ์˜ doubleํ˜• ๋‚œ์ˆ˜ ๋ฐ˜ํ™˜

 

Random rand= new Random();

//booleanํ˜• ๋‚œ์ˆ˜ ์ถ”์ถœ
boolean ranBool = rand.nextBoolean();
System.out.println("booelanํ˜• : " + ranBool);
        
//intํ˜• ๋‚œ์ˆ˜ ์ถ”์ถœ(-2,147,483,648 ~ 2,147,483,647)
int ranInt1 = rand.nextInt();
System.out.println("intํ˜• (๋ฒ”์œ„x) : " + ranInt1);
        
//longํ˜• ๋‚œ์ˆ˜ ์ถ”์ถœ
long ranLong = rand.nextLong();
System.out.println("longํ˜• : " + ranLong);
        
//intํ˜• ๋‚œ์ˆ˜ ์ถ”์ถœ(0~9)
int ranInt2 = rand.nextInt(10);
System.out.println("intํ˜• (0~9) : " + ranInt2);
        
//intํ˜• ๋‚œ์ˆ˜ ์ถ”์ถœ(-10~0)
int ranInt3 = rand.nextInt(11)-10;
System.out.println("intํ˜• (-10~0) : " + ranInt3);
        
//floatํ˜• ๋‚œ์ˆ˜ ์ถ”์ถœ
float ranFloat = rand.nextFloat();
System.out.println("floatํ˜• : " + ranFloat);
        
//doubleํ˜• ๋‚œ์ˆ˜ ์ถ”์ถœ
double ranDouble = rand.nextDouble();
System.out.println("doubleํ˜• : " + ranDouble);

 

 

 

Reference

https://lktprogrammer.tistory.com/114#google_vignette