【问题标题】:srand(time(NULL)): error C4430: missing type specifier - int assumed. Note: C++ does not support default-intsrand(time(NULL)):错误 C4430:缺少类型说明符 - 假定为 int。注意:C++ 不支持默认整数
【发布时间】:2013-09-17 15:42:19
【问题描述】:

我尝试播种 rand() 函数

Why do I always get the same sequence of random numbers with 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++ 不支持 default-int

错误 C2365:“srand”:重新定义;之前的定义是“功能”

【问题讨论】:

  • 无论如何你都应该使用&lt;random&gt;Watch this.
  • 听起来你没有包含ctime来获取time函数。
  • #include #include 没有区别
  • 在这种情况下,您需要发布一些实际代码。没有东西可看,我们几乎无法为您提供帮助。
  • 这是整个代码吗? srand 应该在一个不在全局范围内的函数内。

标签: c++


【解决方案1】:

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

定义可以包含初始化器,这使得int random_integer = std::rand(); 能够工作。

一个明显的治疗方法:

int radom_integer;

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

也就是说,与srand/rand 相比,使用 C++ 随机数生成器类通常会更好。

【讨论】:

  • 并且误导性错误消息是由编译器试图(并且失败)找出srand(time(NULL));在该上下文中的含义引起的。它不认为它可能是一个(非声明)语句,因为语句在函数体之外是不允许的。它可以做出的最接近的猜测是,它是一个格式错误的函数声明,缺少返回类型(在旧式 C 中,该类型隐式为 int)。
猜你喜欢
  • 1970-01-01
  • 2015-01-28
  • 1970-01-01
  • 2017-03-28
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多