Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I'm trying to build a dice program using C++ it isn't displaying my return

The code is printing the greeting and all the messages except the number. I need to see what is being generated by my random number generator.

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

void greeting(int pnum){
       if(pnum == 1) {
           std::cout << "Please press \"ENTER\" to roll the die"; 
       }
       else {
            std::cout << "Please press \"ENTER\" to roll the die AGAIN"; 
       }
        std::cin.ignore();
}

int dieroll(void){
    int ran;
    srand(time(NULL));
    ran = rand()%6+1;
    std::cout << "You have rolled :" << std::endl;
    return ran;
}

int main(void){
    int counter, firstdie, ran;
    char firststart;

    do {
        greeting(1);
        firstdie = dieroll();
    }
 
    while (ran > 0);
    {
        return ran;
    }
    
    std::cin.ignore();
    return 0;
}

I’m a beginner so i’m unsure where to start trouble shooting. I’m looking into making local variables.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

in main you do this

while (ran > 0);
{
    return ran;
}

First you never give ‘ran’ a value, so its either > 0, in which case you exit with a random completion code. Or ‘ran’ is <= 0, in which case you exit with a value of 0.

Its not clear what you are trying to do here, but either way your program terminates immediately

To be clear , a return in main will cause your program to stop immediatley

Then here

int dieroll(void){
    int ran;
    srand(time(NULL));
    ran = rand()%6+1;
    std::cout << "You have rolled :" << std::endl;
    return ran;
}

You intend to print ‘ran’ but in fact do not , you need

    std::cout << "You have rolled :" << ran << std::endl;

I wonder if you think that the ‘ran’ here is the same as the ‘ran’ in main, it is not, there is no relationship between them

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading