【问题标题】:C Programming If Statements Not WorkingC 编程 If 语句不起作用
【发布时间】:2015-08-14 07:25:30
【问题描述】:

我的 if 语句不起作用,我不知道为什么。谁能指出我的错误,谢谢。这只是我为练习而制作的一个有点愚蠢的程序,我在此过程中设置了更多变量。

#include <stdio.h>

main()
{

    //This is a program that determines what circle of hell the user will be put in.  Inspired by Dante's Divine Comedy
    char firstQuestion;

    float total = 0;

    printf("ABANDON ALL HOPE, YOU WHO ENTER HERE\n\n");
    printf("Welcome to the gate of hell. I am going to ask you a series of questions and you will answer them truthfully.\n\n\n");

    printf("I would first like to ask you, do you believe you are a good person?(Y or N)\n");
    scanf_s(" %c", &firstQuestion);
    if (firstQuestion == 'Y'){
        printf("We will see about that.\n");
        total = total + 10;
    }
    else if (firstQuestion == 'N'){
    printf("I'm not surprised.\n");
}
    return 0;

}

【问题讨论】:

  • main() --> int main(void)
  • 顺便说一句,我正在使用 Microsoft Visual Studio。这就是为什么我的 scanf() 是 scanf_s()。
  • 您应该查询=='Y' || ... =='y',因为您的输入区分大小写
  • 另外,您可能还想添加一个返回“无效输入”给用户的 else-path...
  • 对于简单的锻炼计划,您应该使用scanf,它与scanf_s 不同。请参阅下面 Nishant 的答案。

标签: c if-statement


【解决方案1】:

scanf_s() 不是 scanf() 的直接替代品。当输入参数是字符或字符串时,您应该包含缓冲区大小。

scanf_s(" %c", &firstQuestion,1);  //For single character

char s[10];

scanf_s("%9s", s, 10);    //For reading a string

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 2014-03-30
    • 2012-07-16
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多