C++中随机函数rand()和srand()的用法

在C++中,可以使用rand()函数产生随机数。(rand()函数的头文件在中)
具体用法参考下面这篇博客:
https://blog.csdn.net/aaa123524457/article/details/80335010

案例

下面是我自己小的一个小案例

  1. #include <iostream>
  2. using namespace std;
  3. #include <string>
  4. #include <cstdlib>
  5. #include <ctime>
  6. struct Student{
  7. string sName;
  8. int age;
  9. int score;
  10. };
  11. struct Teacher{
  12. string tName;
  13. struct Student sArray[5];
  14. };
  15. //给老师和学生赋值的函数
  16. void allocateSpace(struct Teacher tArray[],int len)
  17. {
  18. string nameSeed = "ABCDE";
  19. for(int i=0;i<len;i++)
  20. {
  21. tArray[i].tName = "Teacher_";
  22. tArray[i].tName +=nameSeed[i];
  23. for(int j=0;j<5;j++)
  24. {
  25. tArray[i].sArray[j].sName = "Student_";
  26. tArray[i].sArray[j].sName +=nameSeed[j];
  27. //在C++中使用rand()随机函数时,需要导入#include <cstdlib>
  28. //用随机数给学生赋值
  29. int random =rand()%61+40;//(0-60)->(40-100)
  30. tArray[i].sArray[j].score = random;
  31. }
  32. }
  33. }
  34. void printInfo(struct Teacher tArray[],int len)
  35. {
  36. for(int i=0;i<len;i++)
  37. {
  38. cout<<"老师的姓名:"<<tArray[i].tName<<endl;
  39. for(int j=0;j<5;j++)
  40. {
  41. cout<<"\t学生的姓名:"<<tArray[i].sArray[j].sName<<
  42. " 学生的分数:"<<tArray[i].sArray[j].score<<endl;
  43. }
  44. }
  45. }
  46. int main()
  47. {
  48. //随机数种子,在使用rand直接生成随机数每次执行的结果都是一样的,只要给它加一个随机种子才能是真正的随机
  49. srand((unsigned int)time(NULL));
  50. //1,创建3名老师的数组
  51. struct Teacher tArray[3];
  52. //2,给3名老师的信息赋值,并且给他们所带的学生数组也赋值
  53. int len = sizeof(tArray)/sizeof(tArray[0]);
  54. allocateSpace(tArray,len);
  55. //3,打印所有老师及所带的学生的信息
  56. printInfo(tArray,len);
  57. return 0;
  58. }