1

My code

#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 file

LIBRARY "square"
EXPORTS
RandNum = randnumber

I call it in excel-vba as function. When i use it, it randoms corectly in first time, but ... When i calculate workbook manually (Fress F9 or re-enter), it does not change number. Why it does not work?

AnThai
  • 11
  • 2
  • `(1 + rand()) % 36 / 1000;` is integer arithmetic –  May 24 '16 at 09:30
  • i don't understand a = (1 + rand() % 36) / 1000; /* just like double formating*/ and i run it correctly in simple empty project. P/s sr (1 + rand() % 36) / 1000 not (1 + rand()) % 36 / 1000;, it my mistake :D – AnThai May 24 '16 at 09:38

1 Answers1

1

srand(time(NULL)) is based on the current time in seconds. So if you call it in less than a second, it will give you the same seed.

To solve this problem you could increase the precision of the time structure used by srand.

#include <sys/time.h>

struct timeval t1;
gettimeofday(&t1, NULL);
srand(t1.tv_usec * t1.tv_sec);

This answer gives more info on the subject

Community
  • 1
  • 1
vianney
  • 161
  • 6
  • Tks for your support. I've found my problem, but I forget that reply your answer. this mistake is caused by un-force formating number '1000' as double and precision of time structure in seconds. – AnThai Jun 03 '16 at 03:02