srand가 왜 여러번 실행이 안될까요??

jmonaco88의 이미지

소스내용입니다.

#include
#include

int Random();

int main()
{
int a, b,c, correct=0, incorrect=0, i;

for(i=0; i<10; i++)
{
a=Random();
b=Random();

printf("%d + %d = ", a, b);
scanf("%d", &c);

if(c == a+b)
{
printf("correct!!\n");
correct++;
}
else
{
printf("incorrect..\n");
incorrect++;
}
}

printf("correct num : %d , incorrect num : %d\n", correct, incorrect);

return 0;
}

int Random()
{
srand(time(NULL));
return rand()%100+1;
}

44 + 44 =

55 + 55 =

이런식으로 반복문 한번 마다 Random함수가 한번만 적용이되네요;;; 이유를 모르겠습니다. ㅠ

HDNua의 이미지

srand()는, rand() 함수를 실행하기 위한 seed 값을 설정하는 함수입니다. 프로그램에서 (int)time(0) 값으로 한 번만 초기화해주어야 합니다.
보통 아래와 같이 씁니다.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int MakeRandom(int max);
 
int main(void)
{
    int i;
    int val;
    const int count = 10;
 
    srand((int)time(0));
 
    for (i=0; i<count; ++i)
    {
        val = MakeRandom(count);
        printf("%d: %d\n", i, val);
    }
 
    return 0;
}
 
int MakeRandom(int max)
{
    return rand() % max;
}

저는 이렇게 생각했습니다.

jmonaco88의 이미지

덕분에 궁굼한 문제점을 해결했습니다 ^^

bushi의 이미지

> srand(time(NULL));
> return rand()%100+1;
>
> 반복문 한번 마다 Random함수가 한번만 적용이되네요;;; 이유를 모르겠습니다. ㅠ
>

time() 의 해상도는 1초 입니다.
random seed 를 같은 값으로 줄 경우, 초기화 이후의 randrom 열은 동일합니다.
코드 중간의 scanf("%d", &c)에 의한 지연 없이 for() 루프가 1초 안에 모두 수행될 경우,
작성하신 MakeRandom() 함수의 반환값은 모두 동일합니다.

반목문 한번 마다 Random 함수가 한번만 적용된 것이 아니라,
scanf("%d", &c) 에서 1초 이상 지연이 됐기 때문에 time(0) 값이 달라져서 random seed 가 변경되는 긍정적인 효과를 경험하셨을 뿐입니다.

프로그램을 통털어 random seed 는 한번만 주는 것이 효율적이고,
time(0) 를 seed 로 하셨을 경우엔 프로그램이 1초 안에 재실행되는 경우에 대한 고려까지 하셔야 합니다.

jmonaco88의 이미지

1초에 대해서는 정확히 이해를 했습니다 ^^

srand((int)time(0));

위에분의 답변처럼 이런식으로 한번만 실행을한후에 (함수안에다가 아니라 main에서 한번만 실행했습니다.)

그 이후에는 rand()만 써서 값을 리턴받아서 빼니까

1초안에 입력값을 마구 입력해도 똑같은 값은 출력이 안되네요 ^^

마지막에

>time(0)를 seed로 하셨을 경우엔 프로그램이 1초 안에 재실행되는 경우에 대한 고려까지 하셔야 합니다.

라는 말이 이해가 안되서 다시 답변 달았습니다 ^^

HDNua의 이미지

Brian W. Kernighan과 Dennis M. Ritchie가 저술한 The C Programming Language에서는,
srand 함수와 rand 함수의 내부가 다음과 같다고 설명하고 있습니다.
아래는 이를 이용해 작성해본 간단한 예제인데, 이를 콘솔에 출력해보시면 무슨 의미인지 이해하실 수 있을 것 같습니다.

#include <stdio.h>
#include <time.h>
 
unsigned int _next = 0;
void _srand(unsigned int seed);
int _rand(void);
 
void SetSeedAndPrint(int i);
 
int main(void)
{
    int i;
 
    for (i=0; i<10000000; ++i)
        SetSeedAndPrint(i);
 
    return 0;
}
 
 
void _srand(unsigned int seed)
{
    _next = seed;
}
int _rand(void)
{
    _next = 1103515245*_next + 12345;
    return (_next/65536)%32768;
}
 
void SetSeedAndPrint(int i)
{
    int result = (int)time(0);
    _srand(result);
    printf("i:%10d, Time: %d, rand(): %d\n", i, result, _rand());
}

저는 이렇게 생각했습니다.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.