I'm making a code to generate a random rank for a college assignment. And the program looks like this:
#include <conio.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
char rankgen()
{
char rank;
int randnum = (rand() % 13) + 1;
// printf("randnum: %d\n", randnum);
if (randnum != 1 || randnum != 11 || randnum != 12 || randnum != 13
|| randnum != 10) {
rank = randnum + '0';
} else {
if (randnum == 10)
rank = 1 + '0';
else if (randnum == 1)
rank = 'A';
else if (randnum == 11)
rank = 'J';
else if (randnum == 12)
rank = 'Q';
else if (randnum == 13)
rank = 'K';
}
return rank;
}
char rankgen2()
{
char rank;
int randnum = (rand() % 13) + 1;
// printf("randnum: %d\n", randnum);
if (randnum != 1 || randnum != 11 || randnum != 12 || randnum != 13
|| randnum != 10) {
rank = randnum + '0';
}
if (randnum == 10)
rank = 1 + '0';
if (randnum == 1)
rank = 'A';
if (randnum == 11)
rank = 'J';
if (randnum == 12)
rank = 'Q';
if (randnum == 13)
rank = 'K';
return rank;
}
int main()
{
srand(time(NULL));
for (int i = 0; i < 30; i++) {
char rank = rankgen();
char rank2 = rankgen2();
printf("%c, %c\n", rank, rank2);
}
return 0;
}
It seems like I can't assign a char into a char variable when using a nested loop or in an if-else statement. I could temporarily fix that by making it not inside any of the loop or any statement. It would help a lot if you explain why does it happen and how to fix it.
You only need one
rankgenfunction (since they both do exactly the same thing), and it should look something like this:Note that as @EugeneSh pointed out, the initial
ifstatement is wrong; since no value can be equal to more than one different value, it will always be false. Because of this, most of the time you return a garbage value inrank. Also, I'm not sure what you meant for your== 10case to do, but I changed it to make the character 'T' (for "Ten").You could also do this with a switch statement like this: