在C51下的随机数生成
/* --------------------------------------------* 描述 : 在 Windows server 2003, vs.net 2003下调试通过
*
* 作者 : e.Studio·zhzkl
* 参考 : rfc4122
* -------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define A 3
int AdvancedLinearCongrutial(int x, int a, int b, int c, int m, int max);
int main(int argc, char* argv[])
{
char* nums = argv[1]; // 取得参数
char mynums[10]; // 预定义10位长度的字符数组, 单片机为8位 应该不会超过这个范围了
int res = 0, pos = 0, length = 0;
// 将字符流转换为Int
//
while(nums[pos] != '\0' )
{
length = length + 1;
pos = pos + 1;
}
pos = 0;
length = length - 1;
while(nums[pos] != '\0')
{
mynums[length - pos] = nums[pos];
pos++;
}
pos = 0;
while(nums[pos] != '\0')
{
int m = 1;
for(int k = 0; k<pos; k++)
{
m = m * 10;
}
res = res + (mynums[pos] - 48) * m;
pos = pos + 1;
}
// 定义随机种子
//
srand(res);
int x = rand(), a = 2, b = 3, c = 5, m = 65536;
// 改进的线性同余算法
int i = AdvancedLinearCongrutial(x, a, b, c, 65536, rand()%100);
printf("i = %d", i);
printf("\tres = %d", res);
return i;
}
// 改进的线性同余算法
int AdvancedLinearCongrutial(int x, int a, int b, int c, int m, int max)
{
for(int i=0; i<max; i++)
{
a = A;
for(int j=0; j<i; j++)
{
a *= A;
}
x = (a*x + (a-1)*c/b)%m;
}
return x;
}
*
* 作者 : e.Studio·zhzkl
* 参考 : rfc4122
* -------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define A 3
int AdvancedLinearCongrutial(int x, int a, int b, int c, int m, int max);
int main(int argc, char* argv[])
{
char* nums = argv[1]; // 取得参数
char mynums[10]; // 预定义10位长度的字符数组, 单片机为8位 应该不会超过这个范围了
int res = 0, pos = 0, length = 0;
// 将字符流转换为Int
//
while(nums[pos] != '\0' )
{
length = length + 1;
pos = pos + 1;
}
pos = 0;
length = length - 1;
while(nums[pos] != '\0')
{
mynums[length - pos] = nums[pos];
pos++;
}
pos = 0;
while(nums[pos] != '\0')
{
int m = 1;
for(int k = 0; k<pos; k++)
{
m = m * 10;
}
res = res + (mynums[pos] - 48) * m;
pos = pos + 1;
}
// 定义随机种子
//
srand(res);
int x = rand(), a = 2, b = 3, c = 5, m = 65536;
// 改进的线性同余算法
int i = AdvancedLinearCongrutial(x, a, b, c, 65536, rand()%100);
printf("i = %d", i);
printf("\tres = %d", res);
return i;
}
// 改进的线性同余算法
int AdvancedLinearCongrutial(int x, int a, int b, int c, int m, int max)
{
for(int i=0; i<max; i++)
{
a = A;
for(int j=0; j<i; j++)
{
a *= A;
}
x = (a*x + (a-1)*c/b)%m;
}
return x;
}