【问题标题】:Issue with for loop, it reads both if and else if statementfor 循环出现问题,它同时读取 if 和 else if 语句
【发布时间】:2014-05-15 18:35:20
【问题描述】:

我的 for 循环有问题。它通过两个数组并比较帐号和 PIN。 if 语句检查帐号和 PIN 的组合是否正确。由于我从原来的(user_Account == accounts[i] && user_Pin != pins[i]) 更改了这部分(user_Account != accounts[i] || user_Pin != pins[i]),因此发生了这种情况。在此之前它运行良好,但我担心如果有人输入错误的帐户,那么程序可能会崩溃,所以我做了这个改变。这是代码的一部分,如果需要,我可以发布更多。请记住一件事,我正在开始上课,所以没有高级更改或建议,我需要当前水平的东西。感谢您的帮助。

for (int i = 0; i < 6; i++)
{
    if(user_Account == accounts[i] && user_Pin == pins[i])
    {
        cout << "You entered correct combination of account and pin number." << endl;
    }
    else if(user_Account != accounts[i] || user_Pin != pins[i])
    {
        cout << "You entered wrong account and/or wrong pin number. Please start over." << endl;
        return 0;
    }
}

【问题讨论】:

  • 如果是if (x) else if (!x),就去掉第二个if。尝试修复逻辑反转以及完全没有必要时,您将省去头疼的问题。
  • 就像 PIN 代表个人识别号码一样,PIN 号码将是个人识别号码...... :)

标签: c++ loops if-statement for-loop


【解决方案1】:

当你从

(user_Account == accounts[i] && user_Pin != pins[i]) 

(user_Account != accounts[i] || user_Pin != pins[i])

你应该已经转换为:

(user_Account != accounts[i] || user_Pin == pins[i])

您实际上正在应用一个名为De Morgan's laws 的东西,至少值得阅读它们的历史:)。

关于您是否应该为帐户失败和 PIN 失败设置单独的 if-else 子句 - 这是一种设计决策。如果有人试图闯入您的“银行”并猜测 PIN 码和帐号,例如从别人的肩膀上看,那么单独的错误消息将帮助他/她更快地找到正确的组合。另一方面,如果(更有可能)客户刚刚输入错误,最好有消息告诉他们。这完全取决于你。

【讨论】:

  • 但是如果有人输入了错误的密码怎么办?还是你认为我应该有 3 个 if 语句?
【解决方案2】:

如果只有两种情况:

  1. 帐号和密码都匹配

  2. 至少有一个不匹配

我只想省去第二个条件的头痛,让检查是这样的:

if (user_Account == accounts[i] && user_Pin == pins[i])
    // accounts match message
else
    // accounts don't match message

另外,你的 for 循环上的一个指针:你可能想确保当一个数组用完时 for 循环不会继续运行,所以你的 for 循环 签名可能是这样的:

for (int i = 0; (i < accounts::size) && (i < pins::size); i++)

【讨论】:

  • 为此我需要一个类,正确的“for (int i = 0; (i
  • 所以我为 (int i = 0; i
  • 如果您使用的是数组,那么您已经在使用一个类。您的数组 accounts 是类 array cplusplus.com/reference/array/array 的对象
猜你喜欢
  • 2020-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多