3

rand()有人知道 Borland C++函数的确切实现吗?

我尝试了以下方法,但结果与我使用真正的 TurboC 4.5 得到的结果不同。自然地,我尝试了不同变体的代码,但没有成功。

unsigned int seed = 1;

void srand(unsigned int newSeed) {
    seed = newSeed;
}

#define MAX_RAND 0x7FFF;

unsigned int lrand()
{
    int a = 22695477;
    int c = 1;
    seed = (a * seed + c);
    return seed;
}

unsigned int rand() {
     return (lrand() >> 16) & MAX_RAND;
}

http://en.wikipedia.org/wiki/Linear_congruential_generator

4

1 回答 1

4

这是我所拥有的,不确定您的编译器版本是否具有相同的rand()and实现srand()

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

/*
  Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland

  srand:
    push      ebp
    mov       ebp, esp
    mov       eax, [ebp + 8]
    mov       [seed], eax
    xor       edx, edx
    mov       [seed + 4], edx ; seed high ?
    call      rand
    pop       ebp
    ret

  rand:
    imul      eax, dword [seed], 015A4E35H
    inc       eax
    mov       [seed], eax
    shr       eax, 10H
    and       eax, 7FFFH
    ret

  seed    dd  015A4E36H, 0
*/

unsigned int myseed = 0x015A4E36;

int myrand(void)
{
  unsigned int t = myseed * 0x015A4E35 + 1;
  myseed = t;
  return (int)(t >> 16) & 0x7FFF;
}

void mysrand(unsigned int seed)
{
  myseed = seed;
  myrand();
}

int main(void)
{
  unsigned t = time(NULL);

  printf("%d %d\n", rand(), myrand());
  printf("%d %d\n", rand(), myrand());
  printf("%d %d\n", rand(), myrand());
  printf("%d %d\n", rand(), myrand());

  srand(t);
  mysrand(t);

  printf("%d %d\n", rand(), myrand());
  printf("%d %d\n", rand(), myrand());
  printf("%d %d\n", rand(), myrand());
  printf("%d %d\n", rand(), myrand());

  return 0;
}

输出:

130 130
10982 10982
1090 1090
11656 11656
23367 23367
13875 13875
12650 12650
13257 13257
于 2013-02-03T13:29:57.243 回答