![](/img/trans.png)
[英]Changing a for loop to a while loop doesn't work correctly (simple code)
[英]Why do while loop doesn't work correctly?
我编写了一些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'
不是同一件事。 '5'
是字符值,而5
是数字值。 字符值取决于字符编码,在当前系统上很可能是ASCII,其中'5'
的数字值为53
( 0x35
)。 '0'
到'9'
是连续的,因此您可以通过在随机数上添加'0'
来绘制字符数字。 for
循环之前将flag
设置为1
,并仅在找到字符时将其清除。 0
, 1
, 2
, 3
和4
。 您可能希望包括所有字符数字? 这是修改后的版本:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char temp[] = { '3', '2', '5', '9', '1' };
const size_t temp_len = sizeof(temp) / sizeof(temp[0]);
char c;
int flag;
srand(time(NULL));
do {
// select a random digit character
c = '0' + rand() % 10;
flag = 1;
for (size_t i = 0; i < temp_len; i++) {
if (temp[i] == c) {
flag = 0;
break;
}
}
} while (flag == 0);
printf("character is: %c\n", c);
return 0;
}
请注意,可以使用memchr()
搜索字符并避免使用容易引起混淆的do
/ while
循环。 这是一个更简单的选择:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main() {
char temp[] = { '3', '2', '5', '9', '1' };
char c;
srand(time(NULL));
for (;;) {
// select a random digit character
c = '0' + rand() % 10;
if (!memchr(temp, c, sizeof temp))
break;
}
printf("character is: %c\n", c);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.