CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Oct 2009
    Posts
    7

    Functions for Die

    So i have been trying to make a program that uses a function to roll a dice. I made the program so that the dice roll is within main but I'd like to make the dice roll a function all in itself so that i can use it for multiple things. This is what i have so far in the file attached and below copied and pasted:

    #include <iostream>
    #include <ctime> // for time function
    #include <cstdlib> // for rand and srand functions
    using namespace std;

    int target, roll;
    long count;

    int rollDie(int target, int roll) {
    long x;
    while(roll != target){
    roll = rand() &#37; 6 + 1;
    x++;
    }
    return x;
    }


    int main(){
    srand((int)time(0));
    cout << "Enter target (ctrl-z to exit): ";
    cin >> target;

    while (cin) {
    //display stats
    cout << endl << "target: " << target << endl;
    cout << "number of rolls: " << rollDie() << endl;

    //prompt and read next target
    cout << "enter target (ctrl-z to exit): ";
    cin >> target;
    }
    //exit
    cout << endl << "Exiting.." << endl;
    return 0;
    }
    Attached Files Attached Files

  2. #2
    Join Date
    Jun 2009
    Location
    oklahoma
    Posts
    199

    Re: Functions for Die

    So... what are you having troubles with?
    I already see you are trying to use your rollDie() function incorrectly.
    It is supposed to accept two arguments, but when you call it, you don't pass anything.

    Second, do not call local variables the same name as global variables.

  3. #3
    Join Date
    Jan 2003
    Posts
    615

    Re: Functions for Die

    Please use code tags and indent your code.
    Before post, make an effort yourself, try googling or search here.

    When posting, give a proper description of your problem, include code* and error messages.

    *All code should include code tags

  4. #4
    Join Date
    May 2009
    Posts
    2,413

    Re: Functions for Die

    One roll of a die,
    Code:
    int rollDie() {
       return rand() &#37; 6 + 1; 
    }

  5. #5
    Join Date
    Oct 2009
    Posts
    7

    Re: Functions for Die

    Alright well I figured it out and like everything it was easier than I was making it. And thanks for the info on code tags I'll use those next time. It was just a matter of taking the loop out of the function and just having the loop in main and each pass through the loop calling the function.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured