I wanted to create a dice game but it's always saying my guess is wrong and idk why. I finally understand how to make the rand function actually random btw :D I think it's because the array isn't storing the strings correctly.
int main()
{
srand(time(NULL));
int dice1 = 1, dice2 = 1, dice3 = 1, sum, key = 0;
int dice4 = 1, dice5 = 1, dice6 = 1, sum2;
char randomnumber[10];
printf("Diceroll-game \n\n");
printf("The first sum is:\n");
dice1 = (rand()%6 + 1);
dice2 = (rand()%6 + 1);
dice3 = (rand()%6 + 1);
sum = dice1 + dice2 + dice3;
printf("%d\n", sum);
printf("Will the next sum of 3 dices be higher(hi), lower (lo) or the same(sa) (hi, lo, sa)?\n");
printf("Type hi, lo or sa\n");
scanf("%c \n", &randomnumber);
dice4 = (rand()%6 + 1);
dice5 = (rand()%6 + 1);
dice6 = (rand()%6 + 1);
sum2 = dice4 + dice5 + dice6;
if (randomnumber == "hi" && sum2 > sum) {
printf("You were right !\n\a");
}else {
if (key == 0) {
printf("You were wrong.");
key = 1;
}
}
if (randomnumber == "lo" && sum2 < sum) {
printf("You were right !\n\a");
}else {
if (key == 0) {
printf("You were wrong.");
key = 1;
}
}
if (randomnumber == "sa" && sum2 == sum) {
printf("You were right !\n\a");
}else {
if (key == 0) {
printf("You were wrong.");
key = 1;
}
}
printf("\nIt's %d", sum2);
return 0;
Can someone help me please. Thank you.
Firstly, You're using wrong format specifier here.
%c
is used to scan onechar
. You need to use%s
for a string. Using wrong format specifier invokes undefined behaviour.Then, the format string you supply to
scanf()
needs to match the input exactly. You don't need anewline
there.Also,
randomnumber
being an array, adding&
while using that asscanf()
argument is not required.Change
to
Secondly, string comaprisons cannot be done using
==
operator. You need to usestrcmp()
to compare two string contents.Change
to