Search code examples
c++c++11randomaddition

How to add up a die roll using user inputted number of die and sides of die in C++?


I'm having trouble with my die roller program not staying within its user-set parameters when it rolls a die. The program is to:

  • be able to take an input in for form nDx or ndx where the d is the letter d or D.

  • n may or not be present. If it is, it represents the number of dice. If not, assume it is a 1.

  • x may or may not be present. If it is, it represents the number of sides on the die. If it is absent, assume it is a 6.

  • If n is absent, x must be present. If x is absent, n must be present.

  • Remember, you need to roll each die individually and then add up the values. Also show the individual dice if n > 1.

  • For example: 2d means roll 2 six-sided dice (2d6). d20 means roll one 20-sided die (1d20)

An example of my output I receive is:

  • Enter number of die being used:
  • 4
  • Enter the number of sides:
  • 5
  • results are:
  • 4d5 = 3
  • 7
  • 11
  • 13
  • 13 ----jGRASP: operation complete.

What I need is the output to be like this:

  • input dice code: 3d6

  • 3d6 = 4 + 2 + 5 = 11

I'm terribly bad at coding this, so please go easy on me. This is what I currently have:

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

using namespace std;

int dice (int nrDice, int nrSides)
{
   int result = 0;
   for (int i = 0; i < nrDice; i++)
   {
      result += ((rand()% nrSides) + 1);
      cout << result << endl;
   }

   return result;
}

int main ()
{  
   int nrDice = 1, nrSides;
   srand(time(0));

   cout << "Enter number of die being used: " << endl;
   cin >> nrDice;

   cout << "Enter the number of sides: " << endl;
   cin >> nrSides;

   cout << nrDice << "d" << nrSides << " = " << dice (nrDice, nrSides) << endl;

   return 0;
}

Solution

  • You just need to output your roll, not cumulative sum:

    int dice (int nrDice, int nrSides)
    {
        const char* sep = "";
        int result = 0;
        for (int i = 0; i < nrDice; i++)
        {
            int roll = ((rand()% nrSides) + 1);
            result += roll;
            std::cout << sep << roll;
            sep = " + "
        }
        std::cout << result << endl;
    
        return result;
    }
    

    Demo

    You already create function :) which is good.

    Now, try that function has one purpose, print or roll die.

    std::vector<int> dice (int nrDice, int nrSides)
    {
        std::vector<int> result;
        for (int i = 0; i < nrDice; i++)
        {
            result.push_back((rand() % nrSides) + 1);
        }
        return result;
    }
    
    void print(std::vector<int>& v, const char* separator)
    {
        const char* sep = "";
        for (auto e : v) {
            std::cout << sep << e;
            sep = separator;
        }
    }
    
    int accumulate(std::vector<int>& v)
    {
        return std::accumulate(v.begin(), v.end(), 0);
    }
    

    Demo