Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement a class called Die that simulates an n-sided die, where n is greater t

ID: 3774626 • Letter: I

Question

Implement a class called Die that simulates an n-sided die, where n is greater than 2 The class should have two constructors, one with one parameter (the numbers of sides), and one with none. The constructor with no parameters should build a 6-sided die. There should be one accessor method which returns the number of sides. There should be a method to simulate a random die roll called Roll. Roll should return an integer value indicating the value ofthe roll. The roll value should be a random number between 1 and m Sides inclusive Your Die class should be created with a .h file, and a .cpp file. You should also write a main code block in a separate .cpp file that instantiates two objects from the Die class and then rolls two dice 10 times.

Explanation / Answer

dice.h

class Dice{
   int m_sides;
  
   public:
       Dice();
       Dice(int s);
       int Roll();
       int getSides();
};

------------------------------

dice.cpp

#include"dice.h"
#include<algorithm>
#include<ctime>

int random(int min, int max) //range : [min, max)
{
static bool first = true;
if ( first )
{
srand(time(NULL));
first = false;
}
return min + rand() % (max - min);
}

Dice::Dice(){
   m_sides = 7;
}

Dice::Dice(int s){
   m_sides = s;
}

int Dice::Roll(){
   return random(1, m_sides+1);
}

int Dice::getSides(){
   return m_sides;
}

--------------------------

main.cpp

#include<iostream>
#include "dice.h"

using namespace std;

int main(int argc, char** argv) {
  
   Dice d6;
   Dice d20(20);
  
   cout<<"6 sided dice: ";
   //Roll with 6 sides
   for(int i=0;i<10;i++){
       cout<<d6.Roll()<<" ";
   }
  
   cout<<" 20 sided dice: ";
   //Roll with 20 sides
   for(int i=0;i<10;i++){
       cout<<d20.Roll()<<" ";
   }
      

return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote