簡體   English   中英

當用戶輸入無效數字時,不會出現錯誤消息

[英]Error message doesn't appear when user enter invalid number

我已經制作了一個簡單的程序,現在我想要輸入“大於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();
}

你應該使用if(math < 0 || math > 100) ......一個數字不能同時> 100且<0。

沒有這樣的數字大於100且小於0。

大於100 = 101,102,103,104

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

你看? 如果您只想允許0到100之間的數字,您需要:

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

編寫的程序存在一些問題。

less than 0 AND more than 100. This is an impossible case and will cause the program to never print the desired message, even when the math grade variable is outside of the desired range. 首先,數學等級的評估是檢查等級是否小於0且大於100.這是一個不可能的情況,並且將導致程序永遠不會打印所需的消息,即使數學等級變量在外面所需范圍。

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

這可以通過使用邏輯||來糾正 (或)代替&&(和)。

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

剩下的問題在於,只有這樣才能檢查數學等級。 可以編寫成績檢查功能,以確保英語和物理等級也在適當的范圍內。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM