C语言,rand()函数生成随机验证码

清疚 2023-07-17 15:39 65阅读 0赞

C语言,生成随机验证码

分析:srand()、rand()函数在头文件中。srand()函数生成随机数种子,time()为系统时间,每次不能设置相同的种子,不然产生的随机数相同,因此选择变化的系统时间作为参数。由于CPU运行速度很快,所以主函数中用Sleep()函数休眠1s,避免前后时间间隔太短,前后种子值相同,生成相同的随机数。

  1. #include <stdio.h>
  2. #include <time.h>
  3. #include <string.h>
  4. #include <windows.h>
  5. #include <stdlib.h>
  6. void identifying_code(char c[],int n)
  7. {
  8. int i,len;
  9. char str[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  10. len=strlen(str);
  11. srand((unsigned)time(0));
  12. for(i=0; i<n; i++)
  13. c[i]=str[rand()%len];//生成str[0~len-1]的随机数
  14. }
  15. int main()
  16. {
  17. char code[7]={ 0};
  18. int i,n;
  19. scanf("%d",&n);
  20. for(i=0; i<n; i++)
  21. {
  22. identifying_code(code,n);
  23. printf("%s\n",code);
  24. Sleep(1000);//休眠1s
  25. }
  26. return 0;
  27. }

发表评论

表情:
评论列表 (有 0 条评论,65人围观)

还没有评论,来说两句吧...

相关阅读