由C到DLL的随机函数complie工作不正常

我的代码

#include <stdio.h> #include <time.h> #include<stdlib.h> float randomnumber(double x) { // when input a number(x). Ex 99.5 // this function will return ramdom a (double)number between 98.2%*x to 101.8%*x double a = 0; srand(time(0)); a = (1 + rand() % 36) / 1000; return x * (0.982 + a); } float _stdcall randnumber(double x) { double a = 0; do { a = randomnumber(x); }while (a > 100 || a == 100); return a; } 

def文件

 LIBRARY "square" EXPORTS RandNum = randnumber 

我把它叫做excel-vba函数。 当我使用它,这是第一次正确随机,但是…当我手动计算工作簿(FREF F9或重新input),它不会改变数字。 为什么它不起作用?

srand(time(NULL))是基于当前时间(以秒为单位)。 所以如果你在不到一秒的时间内调用它,它会给你同样的种子。

为了解决这个问题,你可以提高srand使用的时间结构的精度。

 #include <sys/time.h> struct timeval t1; gettimeofday(&t1, NULL); srand(t1.tv_usec * t1.tv_sec); 

这个答案提供了关于这个问题的更多信息