有人知道Borland C ++ rand()
函数的确切实现吗?
我尝试了以下但是结果与我在真正的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;
}
答案 0 :(得分:3)
这就是我所拥有的,不确定您的编译器版本是否具有rand()
和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