如何生成一个1~20000000的随机数

我写的代码如下:
#include
#include

int main()
{
int a;
srand((unsigned int)time(NULL));
a = rand() % 20000000 + 1;
printf("%d", a);
return 0;
}

输出结果每次都是在之前一次结果中加上几个数,例如上一次运行结果是8502,再运行一次是8507。
感觉不是随机生成的数,因为前两个数字是固定的,那到底要怎么修改代码才能生成一个1~20000000的随机数呢?

随随机数是类型规律,固定的,也就是所谓的属性。
根据随机数类型寻求伪随机数规律,也就人为循环出的随机数,伪随机数规律起筛选的作用,去伪存真,得到银行密码,可以取钱

因为我们是按照时间的规律走的,一秒计算机可以执行很多次,如果我们用while型,因为运行效率快,导致我们误以为是没规律的
无规律型.


#include <iostream>
#include <ctime>
#include <stdlib.h>
using namespace std;
int main()
{
        int a,i=10;
        srand((int)time(NULL));
        
        while (i > 0)
        {
            a = rand() % 100 + 1;
            cout << a << endl;
            i--;
        }
        return 0;

}

因为我们的手动桉数字,所以效率会慢一点,就会按照一定的规律运行
有规律性:


#include <iostream>
#include <ctime>
#include <stdlib.h>
using namespace std;
int main()
{
        int a,i=10;
        srand((int)time(NULL));
        
        /*while (i > 0)
        {*/
            a = rand() % 100 + 1;
            cout << a << endl;
            /*i--;
        }*/
        return 0;

}

少加了一个头文件#include<stdlib.h>

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
    int a;
    srand((unsigned int)time(NULL));
    a = rand() % 20000000 + 1;
    printf("%d", a);
    return 0;
}

你是在什么开发环境之下呢?不同环境下,rand函数返回值的取值范围是不同的
centos7下面,他定义的是 #define RAND_MAX 2147483647
在vs2012下面,他是: #define RAND_MAX 0x7fff

试试看行不?

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int main()
{
    srand(clock());    
    printf("%d\n",rand()%20000000+1);        
    return 0;
}

题主你好:
“------------------------------------------------------------------------------------------------------”
少了个头文件


#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
    int a;
    srand((unsigned int)time(NULL));
    a = rand() % 20000000 + 1;
    printf("%d", a);
    return 0;
}
 

请采纳