【发布时间】:2019-07-09 17:50:14
【问题描述】:
我编写了一些 C 代码来生成一个随机字符并检查该字符是否存在于数组中。如果存在,我想重新生成一个新字符。我使用标志作为指示符并使用do/while 循环来检查此标志,但不幸的是,代码无法按预期工作,并且我得到了一个已存在于数组中的字符。
我需要你的帮助来理解和解决这个问题。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char c;
int num;
int flag = -1;
char temp[5] = { '3', '2', '5', '9', '1' };
srand(time(NULL));
do {
num = rand() % 5;
c = num;
for (int i = 0; i < 5; i++) {
if (temp[i] == c) {
flag = 0;
break;
} else {
flag = 1;
}
}
} while (0 == flag);
printf("number is : %d\n", c);
return 0;
}
【问题讨论】:
-
5是一个数字。'5'是一个字符。两者的区别是'0'。 IE。'5' == 5 + '0' -
那么,我应该怎么做是将for循环中的条件修改为
c if(temp[i] == c+'0' )或什么? :D 如果你给我一个例子,我会很感激 :) -
^ 这是解决方案之一。
-
@Ahmedhamdy:您可以通过点击分数下方的灰色复选标记来接受答案