我正在编写代码来为大学作业生成随机排名。程序如下所示:
#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;
}
在使用嵌套循环或 if-else 语句时,似乎我无法将 char 分配给 char 变量。我可以通过使它不在任何循环或任何语句中来临时解决这个问题。如果您解释为什么会发生这种情况以及如何解决它,将会有很大帮助。