gpt4 book ai didi

c - Borland C rand() 的实现

转载 作者:行者123 更新时间:2023-12-04 03:52:16 27 4
gpt4 key购买 nike

有人知道 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;
}

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

最佳答案

这是我得到的,不确定您的编译器版本是否具有相同的 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

关于c - Borland C rand() 的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14672358/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com