srand(time(NULL)):错误 C4430:缺少类型说明符 - 假定为 int.注意:C++不支持默认整数

srand(time(NULL)): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

本文关键字:int 注意 不支持 整数 默认 C++ 类型 错误 NULL time C4430      更新时间:2023-10-16

我试图为 rand() 函数播种

为什么我总是得到与 rand() 相同的随机数序列?

#include "stdafx.h"
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <windows.h>
#include <string> 
#include <shlobj.h>
#include <Shlwapi.h>
#include <stdio.h>
#include <aclapi.h>
#include <tchar.h>
#include <iostream>
#include <fstream>
#include <curl/curl.h>
#include <future>
#include <stdlib.h>
#include <random>
#include <ctime>
#include <time.h>  
#include <Lmcons.h>
srand(time(NULL)); 
int random_integer = std::rand(); 

但是 srand(time(NULL)) 返回:

错误 C4430:缺少类型说明符 - 假定为 int。注意:C++不支持默认整数

错误 C2365:"srand":重新定义;以前的定义是"函数"

现在的问题是调用srand(time(NULL));需要进入函数内部 - 在全局范围内,你不能只编写将执行的代码 - 你只能声明/定义函数,变量等。

定义可以包括初始值设定项,这是允许int random_integer = std::rand();工作的原因。

一种明显的治疗方法:

int radom_integer;
int main() { 
    srand(time(NULL));
    random_integer = rand();
    // ...
}

也就是说,您通常最好使用 C++ 随机数生成器类而不是 srand/rand

相关文章: