【发布时间】:2021-02-08 17:20:02
【问题描述】:
所以代码运行,并且在大多数情况下,执行我希望它执行的操作。唯一的问题是当密码等于 1000 时打印语句“尝试密码:1000”在计算机已破解密码的语句之前不打印,我知道这是因为它们彼此相等,所以代码跳过到 else if 语句。有没有办法让“尝试密码:1000”在它打印出它破解密码之前打印出来?
#include <stdio.h>
#include <stdbool.h>
int password;
int attack = 1000;
int num = 1;
bool repeat = true;
int main()
{
printf("Please enter a 4 digit password:\n");
scanf("%4d", &password);
while (repeat)
{
if (password < 1000 || password > 9999)
{
printf("Please enter a 4 digit password.\n");
scanf("%4d", &password);
}
if (attack != password)
{
printf("Trying password: %4d\n", attack++);
num=num+1;
}
else if (attack == password)
{
printf("Computer cracked the password in %4d tries\n", num);
repeat = false;
}
}
return 0;
}
【问题讨论】:
-
将
printf("Computer cracked the password in %4d tries\n", num);移动到while循环结束后 - 就在return 0;之前 -
我刚刚试了一下,仍然没有打印出“尝试密码:1000”。将整个 else if 语句移到工作之外,如果是,我将在哪里放置 repeat = false 来结束循环?
-
同时删除
if (attack != password) {}(但不是括号内的内容),以便它每次都执行该代码。 -
您认为
0123是四位密码吗?您的代码会将其视为三位数密码。 -
请edit您的问题并显示一些示例输入、您获得的相应输出和预期输出。如果您输入了正确的密码
1000,您是否需要消息Trying password: XXXX和消息Computer cracked the password in NNNN tries?如果从示例输入和输出中还不清楚,请在问题中澄清这一点,
标签: c