编译C++代码,提示:错误:‘srand’在此作用域中尚未声明

文章展示了在C++编程中遇到srand和rand未声明的错误,解决方案是包含头文件<cstdlib>。代码示例解释了如何使用srand设置随机数种子并生成随机数数组,然后在主函数中打印这些随机数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[root@bogon C++]# g++ test_array_function.cpp -o test_array_function
test_array_function.cpp: 在函数‘int* getRandom()’中:
test_array_function.cpp:12:33: 错误:‘srand’在此作用域中尚未声明
   srand( (unsigned)time( NULL ) );
                                 ^
test_array_function.cpp:15:17: 错误:‘rand’在此作用域中尚未声明
     r[i] = rand();


解决方案:

增加:#include <cstdlib>

C++中头文件cstdlib是是C++的函数库, 等价于C中的<stdlib.h>。可以提供一些类型、函数与常量:

1、类型:size_t, wchar_t, div_t, ldiv_t, lldiv_t。

2、常量:NULL, EXIT_FAILURE, EXIT_SUCCESS, RAND_MAX, MB_CUR_MAX。

3、函数:calloc()、free()、malloc()、realloc()、rand()、atoi()、atol()、rand()、srand()、exit()。

[root@bogon C++]# cat test_array_function.cpp 
#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

// 要生成和返回随机数的函数
int * getRandom( )
{
  static int  r[10];

  // 设置种子
  srand( (unsigned)time( NULL ) );
  for (int i = 0; i < 10; ++i)
  {
    r[i] = rand();
    cout << r[i] << endl;
  }

  return r;
}

// 要调用上面定义函数的主函数
int main ()
{
   // 一个指向整数的指针
   int *p;

   p = getRandom();
   for ( int i = 0; i < 10; i++ )
   {
       cout << "*(p + " << i << ") : ";
       cout << *(p + i) << endl;
   }

   return 0;
}
[root@bogon C++]#
[root@bogon C++]# g++ test_array_function.cpp -o test_array_function
[root@bogon C++]# ./test_array_function 
342705179
1735631723
1884932714
1409631640
1175186931
1046409182
1148664731
1778548432
628655475
627766212
*(p + 0) : 342705179
*(p + 1) : 1735631723
*(p + 2) : 1884932714
*(p + 3) : 1409631640
*(p + 4) : 1175186931
*(p + 5) : 1046409182
*(p + 6) : 1148664731
*(p + 7) : 1778548432
*(p + 8) : 628655475
*(p + 9) : 627766212

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值