gpt4 book ai didi

c - 为什么使用不同的循环会得到不同的输出?

转载 作者:行者123 更新时间:2023-11-30 17:06:55 25 4
gpt4 key购买 nike

我编写了一个代码,输入四个字母,并在每个字母的位置打印一个“*”,就像密码一样。工作代码是这样的:

#include <stdio.h>
#include <conio.h>
int main()
{
int c = 0;
char d[4];
printf("Enter a character:");
while (1)
{
if (_kbhit())
{
d[c] = _getch();
printf("*");
c++;
}
if (c == 4)
break;
}
system("cls");
for (c = 0; c <= 3; c++)
printf("%c", d[c]);
}

现在我有两个问题:1) 为什么当我将循环更改为时会得到四个╠:

for (c = 0; c <= 4;c++)
{
if (_kbhit())
{
d[c] = _getch();
printf("*");
}
}

和2)当我将第二个循环的上限更改为c<=4时,为什么最后会得到一个额外的╠?

第二个循环是这样的:

for (c = 0; c <= 3; c++)
printf("%c", d[c]);

最佳答案

因为无论 _kbhit() 返回 true 还是 false,for 循环都会迭代 4 次。 while 循环直到 _kbhit() 返回 true 4 次

对于第二个问题,d[4]超出了数组范围,相同的值只是巧合

关于c - 为什么使用不同的循环会得到不同的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34361190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com