jeudi 27 octobre 2016

C++ : curious return value from a rand() in Dice.h

I know there is a lot of question relative to rand() but none solves my problem.

I have a Dice.h implemented has follow :

#pragma once
#ifndef DEF_DICE
#define DEF_DICE

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

class Dice
{
public:

//Constructors
Dice();
Dice(int nbFaces);

//Destructor
~Dice();

//Return the result of a roll
int roll();

protected:

//The number of faces of this dice
int m_faces;
};

#endif // !DEF_DICE

In Dice.cpp I have this :

#include "stdafx.h"
#include "Dice.h"

Dice::Dice() : m_faces(6)
{

}

Dice::Dice(int nbFaces) : Dice()
{
    m_faces = nbFaces;
}

Dice::~Dice()
{
}

int Dice::roll()
{
    int roll(rand()*m_faces + 1);
    return roll;
}

And my main looks like this :

#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include "Dice.h"

using namespace std;

int main()
{
    srand(time(0));

    Dice d6;
    cout << d6.roll() << endl;

    int test(rand() % 6 + 1);
    cout << test << endl;


    return 0;
}

Nothing hard, isn't it ? Just a dice, made with 6 faces through default constructor...

But why the heck d6.roll() returns something like 140456 (always different but always about hundred of thousands) ??? The value of test is good (between 1 and 6)...

I tried with srand(time(0)) in the constructor but it's the same problem.




Aucun commentaire:

Enregistrer un commentaire