随机数

while (n) 其实等同于 while (n != 0)

goto 随机数生成(头文件 stdlib.h) : rand 函数 需要头文件 stdlib.h返回伪随机数

#include <stdio.h>
#include <stdlib.h>
int main()
{
  printf("%d", rand());
  return 0;
}

原理:rand是依靠对“种子”基准值运算生成的伪随机数 srand函数 初始化“种子“(随机数生成器)

原型:void srand (unsigned int seed) 程序在使用rand生成随机数之前会调用srand初始化生成的种子,种子变,伪随机数就变

int main{
srand(1);
printf("%d",rand());

return 0;
}

time 函数(头文件time.h) 因为时间在不断变化,所以可以用时间作为种子,改变随机数

time_t time(time_t *timer);

time_t * timer为指针参数,不用时用NULL

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
    srand((unsigned int)time(NULL));
    printf("%d",rand());

    return 0;
}

在现代 C++ 标准(C++11 及以后)和安全规范(如 CERT C++ 规则 MSC30-C 和 MSC50-CPP)中,rand() 已经被明确标记为不推荐甚至禁止使用(会报警)

使用 Hugo 构建
主题 Stack 由 Jimmy 设计