简体   繁体   English

优化我的代码/程序哪里出错了?

[英]Refine my code/program where did I go wrong?

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    int LordIronhead = 0; 
    char answer;

    cout<<"Is Lord Ironhead present? Y/N.\n";
    cin >> answer;

    if (answer == 'Y')
    {
        LordIronhead=0;
    }
    else if (answer == 'N')
    {
        LordIronhead= LordIronhead+1;
    }

    cout<< ""<<LordIronhead<<"\n"; 

    system("PAUSE");
    return 0;
}

Every time I run the program and If I answer NO (N) the result is always 0 instead of 1 (LordIronhead = LordIronhead + 1) 每次运行程序时,如果我回答“否(N)”,则结果始终为0,而​​不是1(LordIronhead = LordIronhead + 1)

May I know where my error is? 我可以知道我的错误在哪里吗?

Your code is fine in principle, but you might run into issues with the two-valued logic of 'answer' being checked against 'Y' and against 'N' with no fall-through case. 您的代码原则上是可以的,但是您可能会遇到问题,即对“ Y”和“ N”两个值逻辑的“答案”进行检查,而没有掉线的情况。 I suspect you are running into EOL or case or character conversion issues, falling through both if's and thereby never changing the Lord. 我怀疑您遇到EOL或大小写或字符转换问题,同时遇到了两种情况,因此永远都无法改变主。

For showing the problem, try an else statement: 为了显示问题,请尝试else语句:

else if (answer == 'N')
{
     LordIronhead= LordIronhead+1;
} else {
     std::cout << "Invalid answer '" << answer << "'" << std::endl;
}

Your code is correct but is sensitive to the case of user input (it treats user input of N and n differently). 您的代码是正确的,但是对用户输入的大小写敏感(对Nn用户输入进行不同的处理)。 You'd remove a possible source of user confusion by converting the input to a known case before checking it. 您可以通过在检查之前将输入转换为已知案例来消除可能造成用户混乱的原因。 You can do this using either toupper or tolower 您可以使用上层下层来进行此操作

cin >> answer;
answer = toupper(answer);

I just tried this myself and found that if I answered NI got the expected answer (1). 我自己尝试了一下,发现如果我回答了NI,则得到了预期的答案(1)。 If I hit n, however, it came back as 0. Are you sure you're hitting N and not n? 但是,如果我击中n,则返回0。确定要击中N而不是n吗?

最好使用1和0而不是N和Y。它在系统中更容易识别

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM