当用户输入无效号码时,不会显示错误消息

时间:2014-08-21 14:03:26

标签: c

我制作了一个简单的程序,现在我想要输入“大于100且小于0”的数字时,它应显示无效数字的消息。

int math,eng,phy;
float f,h;
printf("Enter math marks:");
scanf("%d",&math);
if (math<0 && math>100)
{
    printf("You have entered invalid number");
}
printf("Enter eng marks:");
scanf("%d",&eng);
printf("Enter phy marks:");
scanf("%d",&phy);
f=math+eng+phy;
if (f>=90 && h<=100)
{
    printf(" You got A grade\n");
}
h=f/300*100;
printf("Your obtained marks=%f\n",f);
printf("Your  percentage=%f\n",h);
getch();
}

3 个答案:

答案 0 :(得分:5)

您应该使用if(math < 0 || math > 100) ...号码不能&gt; 100和&lt; 0同时。

答案 1 :(得分:4)

没有这样的数字大于100而小于0。

大于100 = 101,102,103,104

小于0 = -1,-2,-3

你知道吗?如果您只想允许0到100之间的数字,则需要:

if(x > 0 && x < 100){ /* Right number */ }

答案 2 :(得分:2)

编写的程序存在一些问题。

首先,对数学成绩的评估是检查成绩是否同时小于0且大于100.这是一个不可能的情况,会导致程序永远不会打印出所需的消息,即使数学等级变量超出所需范围。

if (math < 0 && math > 100)
    {
        printf("You have entered invalid number");

这可以通过使用逻辑||来纠正(或)代替&amp;&amp; (和)。

if (math < 0 || math > 100)
    {
        printf("You have entered invalid number");

剩下的问题在于,只有这样才能检查数学等级。可以编写成绩检查功能,以确保英语和物理等级也在适当的范围内。