관리 메뉴

A seeker after truth

sololearn C++ tutorial: Functions 배운 내용 메모 본문

Programming Language/C++

sololearn C++ tutorial: Functions 배운 내용 메모

dr.meteor 2019. 11. 14. 23:56

<Random function>

you can access a pseudo random number generator function that's called rand().

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
  cout << rand();
}

 

Use the modulo (%) operator to generate random numbers within a specific range.
The example below generates whole numbers within a range of 1 to 6.

int main () {
  for (int x = 1; x <= 10; x++) {
  cout << 1 + (rand() % 6) << endl;
  }
}

/* Output: 
6
6
5
5
6
5
1
1
5
3
*/

srand()는 seed값 줘서 다른 인스턴스 혹은 세트를 만드는 느낌이라는 것 이미 이해했지? 혹시 잊으면 검색해서 다시 공부하면 되고.

보통 시드로 time값 준다는건 알 것이고.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main () {
  srand(time(0));

  for (int x = 1; x <= 10; x++) {
    cout << 1 + (rand() % 6) << endl;
  }
}

time(0) will return the current second count, prompting the srand() function to set a different seed for the rand() function each time the program runs.

 

 

call by value시, a copy of the argument is passed to the function, the original argument is not modified by the function.