【问题标题】:Having problem in taking an input of a character value if - else programif - else 程序在输入字符值时遇到问题
【发布时间】:2020-06-16 10:48:49
【问题描述】:

这是我的代码。问题是 - 编写代码以根据学生的出勤率检查学生是否有资格参加考试。如果学生的出勤率超过 75,他有资格参加考试,否则,他/她将被询问他/她是否有健康状况。如果是,他将被允许,否则不允许。请帮帮我。我无法在 if 语句中提供输入。

    int main()
    {
    char response;
    int clshld,per;
    int clsatnd;

    clshld = 330;   //total no of class held
    printf("no of class attended\n");
    scanf ("%d", &clsatnd);
    per=(clsatnd*100)/clshld;    //percentage formula
    printf ("\nattendence percentage is %d", per);

    if (per<75)
    {
        printf ("\ndo you have  a medical condition??");
        scanf ("%c", &response);
        if (response =='y')
        {
            printf ("\nyou can sit in the exam");
        }

        else 
        {
            printf ("\nattendence too low ! you can't sit in the exam.'");
        }
    }
    else
    {
        printf ("\nyou are eligible to sit in the exam.");
    }
    return 0;
    }

【问题讨论】:

标签: c character scanf


【解决方案1】:

试试这个:

#include<stdio.h>

int main()
{
    char response;
    int clshld,per;
    int clsatnd, trash;

    clshld = 330;   //total no of class held
    printf("no of class attended\n");
    scanf ("%d", &clsatnd);
    scanf("%c", &trash);
    per=(clsatnd*100)/clshld;    //percentage formula
    printf ("\nattendence percentage is %d", per);

    if (per<75)
    {
        printf ("\ndo you have  a medical condition?? ");
        scanf ("%c", &response);

        if (response =='y')
        {
            printf ("\nyou can sit in the exam");
        }

        else
        {
            printf ("\nattendence too low ! you can't sit in the exam.'");
        }
    }

    else
    {
        printf ("\nyou are eligible to sit in the exam.");
    }

    return 0;
}

【讨论】:

  • 有没有已知错误的列表可以分享?
  • 我的意思是,'fflush(stdin)' 会导致什么?
  • 谢谢先生。你能解释一下为什么在整数字符串中添加一个字符变量吗??
  • 因为使用 scanf("%c", &trash); ,您从标准输入中删除 \n 并且程序的流程按预期继续
猜你喜欢
  • 1970-01-01
  • 2011-07-03
  • 2018-12-09
  • 1970-01-01
  • 2015-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-05
相关资源
最近更新 更多