C++中一些无法解释的错误
Some unexplained errors in C++
我有以下代码:
#include <cstdlib>
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int a,n,count;
count=0; randomize();
a=1+random(100);
cout<<"Enter A No. Between 1 to 100";
do
{
cin>>n;
count++;
if(n>a)
cout<<"Enter a lower no.";
else if(n<a)
cout<<"Enter a higher no.";
}while(n!=a);
cout<<count;
system("PAUSE");
return EXIT_SUCCESS;
}
错误为:
- E: \c++\main.cpp在函数"int main()"中:
- 10 E:\c++\main.cpp"randomize"未声明(首先使用此函数)
- (每个未声明的标识符对于它出现在中的每个函数只报告一次。)
- 11 E:\c++\main.cpp"random"未声明(首先使用此函数)
有人能帮我理解为什么会出现这些错误吗?
randomize()
不是标准的C++函数,您必须使用srand(something)
来为随机数生成器种子,其中something
通常是当前时间(time(0)
)。
此外,random()
不是标准功能,您必须使用rand()
所以,像这样的东西(清理了一点):
#include <ctime>
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
srand(time(0));
int n, count = 0;
int a = 1 + (rand() % 100);
cout << "Enter A No. Between 1 to 100";
do
{
cin >> n;
count++;
if (n>a)
cout << "Enter a lower no.";
else if (n<a)
cout << "Enter a higher no.";
} while(n!=a);
cout << count;
system("PAUSE");
return EXIT_SUCCESS;
}
您使用的是一个名为"randomize"的函数(此处:count=0; randomize();
)-编译器不知道在哪里可以找到这个函数,因为它没有在代码中定义,也没有在包含的任何标头中定义。
我怀疑你想要srand()
和rand()
。
例如,您可以像下面这样重写现有的代码。要使用此代码,您还需要在包含的内容中使用#include <time.h>
:
int main()
{
int a,n,count;
count=0;
srand(time(NULL)); // use instead of "randomize"
a = 1 + (rand() % 100);
// ... Rest of your code
srand
和rand
。
CCD_ 13和CCD_。
标准C中没有randomize()
和random()
函数。也许你指的是srand()
和rand()
?
看看这个问题,关于如何在给定范围内正确地"随机化"一个数字。rand() % N
不一致地给出[0,N)范围内的数字。
如果你有一个包含<random>
的C++11编译器(如果你没有,你可以使用Boost库中的boost::random
),你可以用这个类来获得更好的伪随机数:
#include <ctime>
#include <random>
class rng
{
private:
std::mt19937 rng_engine;
static rng& instance()
{
static rng instance_;
return instance_;
}
rng() {
rng_engine.seed(
static_cast<unsigned long>(time(nullptr))
);
};
rng(rng const&);
void operator=(rng const&);
public:
static long random(long low, long high)
{
return std::uniform_int_distribution<long>
(low, high)(instance().rng_engine);
}
};
然后你用这个来获得[a,b]
区间中的随机数:
long a = rng::random(a, b);
您不需要手动设置种子,因为它将在第一次调用时设置种子。
相关文章:
- xmake总是报告:错误:无法获取cxx的程序,为什么
- 无法在我的堆排序代码中找到错误.无法正确执行.C++
- VS 2015 链接错误 无法构建依赖于 libcurl 的项目
- 错误:无法解析对重载函数的引用;你的意思是调用它吗?
- VI工作室代码错误无法打开输出文件主.exe
- 为什么即使我声明了朋友类,我也会收到错误"无法访问类中声明的私人成员"
- JavaCPP 错误:无法将参数"1"的"char*"转换为"Abc*
- 构建失败错误:无法使用 qibuild 构建C++ SDK Helloworld
- v8::HandleScope::CreateHandle() # 中的致命错误无法在没有 HandleScope 的情
- 链接器错误:无法解析构造函数
- 错误:无法解析对重载函数的引用
- C 无法解释的类“尚未声明”错误,这是由于名称空间而导致的
- 无法解释的链接器错误
- C++中一些无法解释的错误
- 我的代码中出现了无法解释的错误
- Visual Studio 中无法解释的语法错误
- 编译简单类函数时无法解释的错误?C++
- C++分析器源代码中出现无法解释的错误
- 命名空间 thrust::system::cuda::thrust 中无法解释的错误,特别是在 "system_error" 和 "cuda_category" 中
- C++无法解释的错误:错误:令牌之前的预期初始值设定项'&'