How can I fix this custom dice roll program to work correctly?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • conman2495
    New Member
    • Oct 2014
    • 2

    How can I fix this custom dice roll program to work correctly?

    I need to write a program that will prompt the user to input a number-sided dice and a number of rolls, and then it will output all of the rolls in a sequence. The program I have written will get the number of rolls correct, but something goes wrong with the number-sided dice. It will output numbers in the 100s for a 6-sided dice. Here's my code, does anyone know how to fix this? (My 'y' integer is the one for the number sided die).
    Code:
    #include <stdio.h> 
    #include <time.h> 
    int rolldie(); 
    
    int main(){ 
    int x, n;
    double y;
    printf ("What sided dice do you want to roll?... %d");
    scanf ("%d", &y);
    printf("How Many Rolls do You Want?... %d");
    scanf("%d", &n);    
    srand(time(0));
    for(x=0;x<n;x++) 
    printf("%d ",rolldie()); 
    return 0; 
    } 
    int rolldie(){ 
    return 1 + rand() %'y' ; 
    }
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    I'm surprised you're not getting compiler errors and warnings.
    1. The printf calls on lines 8 and 10 each include %d, but do not pass a corresponding argument.
    2. Line 9 uses %d to scanf a value for y, but y is a double. %d is only for ints.
    3. Line 18 in rolldie() references y, but y is not defined within the scope of that function.
    4. Line 18 says "... % y", but the % modulo operator only works properly with integer operands.
    5. lLine 18 says 'y' (note the single quotes). This is the character constant lower-case-y, not the value of a variable.

    Comment

    Working...