【问题标题】:I cant figure out what my condition needs to be regarding characters我无法弄清楚我的角色需要什么条件
【发布时间】:2017-12-13 17:57:22
【问题描述】:

所以我一直试图弄清楚如何为我的 if 语句使用正确的条件(我知道代码本身有些丑陋,但我关心 atm 的条件)。只要“theguess”(用户输入的字符)在第一个 if 语句中等于“H”或“h”,如果它在第二个 if 中等于“T”或“t”,我希望它进入 if 语句声明,并且如果它不等于第三个的“H”、“h”、“T”或“t”。我以前有||而不是 && 但这也没有用。请阻止我

将字符输入或存储到变量中没有问题,只是我的逻辑有缺陷。

编辑:我决定尝试 && 的原因是因为它解决了其他人提出的类似问题。抱歉,笨拙的代码逻辑与我想要的不匹配。

    if (theguess == ('H') && ('h'))
        {
            P1score -= 5;
            puts("-5 Points!");
        }
        if (theguess == ('T') && ('t'))
        {
            P1score += 10;
            puts("+10 Points!");
        }
        if (theguess != ('H') && ('h') && ('T') && ('t'))
        {
            return 0;
        }

【问题讨论】:

  • 1.你的语法是错误的。任何基本教程都将涵盖正确的语法,只是猜测无济于事... 2. 您的描述说“等于 'H' OR 'h',但您的代码使用了 AND。
  • 使用这个语法:if (theguess == 'H' || theguess == 'h') 等等。
  • 试过使用else if?
  • 对于第一个 if,theguess 等于 Htheguess 等于 h。祝你好运。
  • 我投票决定将此问题作为题外话结束,因为它是关于懒惰阅读教程...:/

标签: c if-statement char conditional-statements


【解决方案1】:

这里是错误,

if (theguess == ('H') && ('h'))

应该是

if (theguess == ('H') || theguess == ('h'))

你为什么不使用 switch..case??

【讨论】:

  • “这里有错误”——错误是什么?这是完全有效的 C。请更明确。
  • 显然没有语法错误,但由于 OP 需要检查值是 'H' 还是 'h',因此 OPs 语句将被视为“if (theguess == ('H' ) && 真)"
  • 我已经在 switch 语句中使用了这段代码,并试图不让自己感到困惑。感谢您的帮助。我没有意识到 || 之后您必须再次放置变量 ==。 :)
  • 显然,这不是错误。这不是 OP 想要做的。
  • @babon-- 确定这是一个错误;不是编译器错误,而是逻辑错误、编码错误或错误,如果您愿意的话....
【解决方案2】:

您正在尝试检查输入的字符是“h”还是“H”,那么为什么要使用“AND”运算符?

您没有正确给出条件。尝试如下它会工作。

#include<stdio.h>
 int main()
 {
    char thought;
    float P1score=0.0;
    printf("Enter your thought\n");
    scanf("%c",&thought);
    if(thought=='h' || thought=='H')
    {
            P1score -= 5;
        puts("-5 Points!");
    }
    else if (thought=='T'||thought== 't')
    {
        P1score += 10;
        puts("+10 Points!");
    }
    else
    {
            return 0;
    }
}

【讨论】:

  • 你应该经常检查scanf的返回。如果用户通过按ctrl+d(或windoze 上的ctrl+z)取消输入,则从那时起您将有未定义的行为(在这种情况下,您将从初始化thought 中受益,就像您对P1score 所做的那样)。您只需要一个简单的if (scanf("%c",&amp;thought) != 1) {..handle error..}
【解决方案3】:

试试这个。你必须使用/||因为如果你给大写或小写,它会满足。如果有效,请给我一个。

if (theguess == ('H') || theguess == ('h'))

    {

        P1score -= 5;

        puts("-5 Points!");

    }

   else if (theguess == ('T') || theguess == ('t'))

    {

        P1score += 10;

        puts("+10 Points!");

    }

    else 

    {

        return 0;

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多