【问题标题】:How can I get my code to print out a statement that gets skipped in my code?如何让我的代码打印出在我的代码中被跳过的语句?
【发布时间】: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


【解决方案1】:

问题是attack 已经从值 1000 开始,因此检查 else if (attack == password) 立即为真,并且您打印出尝试攻击值的语句甚至永远不会被访问。

你应该移动语句

printf("Trying password: %4d\n", attack);

到您的while 循环的开头,并将attack++ 放在末尾。

另外:请参阅 this question 以了解为什么您应该始终检查 scanf 的返回值。我的意思是,如果你下定决心使用scanffgets 几乎总是更好的选择。

【讨论】:

  • 谢谢我最终使用了您建议的语句,并在代码打印计算机破解密码之前放置了一个嵌套的 if 语句,从而解决了问题。 else if (attack == password) { if (password == 1000) printf("尝试密码:%4d\n", attack); printf("计算机在 %d 次尝试中破解了密码\n", num);重复=假; }
  • @JesseHix 如果有效,请随时单击投票箭头附近的复选标记图标将我的答案标记为“已接受”。
猜你喜欢
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-23
  • 1970-01-01
  • 2021-04-20
  • 2022-10-02
  • 1970-01-01
相关资源
最近更新 更多