I'm attempting to work with functions for the first time in C. I'm trying to write a classic roll the dice game that rolls a die 10,000 times and then prints out how many times each number has been rolled using functions.
In the code below I keep getting the error code "Expected expression" when trying to set result= roll_die (int num_sides);
. It says that it's occurring on the int
. When I remove int
I get the error code "Use of undeclared identifier 'num_sides' ". How can I fix this?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int roll_die(int num_sides){
num_sides = rand() % 6;
num_sides = num_sides + 1;
return num_sides;
}
int main(void)
{
srand((int)time(0));
unsigned int counter, result, num1=0, num2=0, num3=0, num4=0, num5=0, num6=0;
unsigned int num_rolls = 10000;
for(counter=0; counter<=num_rolls; counter++)
{
result = roll_die (num_sides);
if(result==1)
num1++;
else if(result==2)
num2++;
else if(result==3)
num3++;
else if(result==4)
num4++;
else if(result==5)
num5++;
else if(result==6)
num6++;
else{
printf("Error occurred. \n"); return 0;
}
}
printf("Number of 1s rolled: %d \n", num1);
printf("Number of 2s rolled: %d \n", num2);
printf("Number of 3s rolled: %d \n", num3);
printf("Number of 4s rolled: %d \n", num4);
printf("Number of 5s rolled: %d \n", num5);
printf("Number of 6s rolled: %d \n", num6);
}
Aucun commentaire:
Enregistrer un commentaire