C++中一些无法解释的错误

Some unexplained errors in C++

本文关键字:错误 无法解释 C++      更新时间:2023-10-16

我有以下代码:

#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
您尝试调用的方法称为srandrand

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);

您不需要手动设置种子,因为它将在第一次调用时设置种子。