[英]Why does my first if statement work, but my else if statement after it doesn't work
為什么我的第一個if語句有效,而我的if語句卻無效? 只是希望有人能看到我可能會丟失的東西。 當我輸入800到1800之間的代碼時,代碼仍然可以正常運行,但是當我輸入600時,它跳轉到我的else語句,即我以非法格式輸入了代碼。
if ((time_start >= 800) && (time_start <= 1800))
{
cout << "How many minutes did your call last? ";
cin >> minutes;
cost = minutes * 0.40;
cout << setprecision(2) << fixed << cost;
system("pause");
keepgoing = false;
}
else if ((time_start < 800) && (time_start > 1800))
{
cout << "How many minutes did your call last? ";
cin >> minutes;
cost = minutes * 0.25;
cout << setprecision(2) << fixed << cost;
system("pause");
keepgoing = false;
}
else if ((time_start < 800) && (time_start > 1800))
一個數字不可能小於800且大於1800。我假設您的意思是:
else if ((time_start < 800) || (time_start > 1800))
您有一個“邏輯錯誤” :使用||
而不是&&
在else if
。 這是根本不可能的數量要小於800和大於1800 在同一時間 。
我一問到這個問題,我就意識到我的第二個if語句應該是or或||。 語句而不是&&。
更改
否則如果((time_start <800)(time_start> 1800
至
否則((time_start <800)||(time_start> 1800
您可以將代碼簡化為此,否則不需要語句。 將值存儲在系數變量中,這需要在定義之前
// else coef (default value)
float coef = 0.25;
if ((time_start >= 800) && (time_start <= 1800))
{
coef = 0.40; // if true
}
cout << "How many minutes did your call last? ";
cin >> minutes;
// use coef here and remove duplicate calls
cost = minutes * coef;
cout << setprecision(2) << fixed << cost;
system("pause");
keepgoing = false;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.