2015-10-06 34 views
-1

爲什麼我的第一個if語句的工作,但我的其他if語句不?只希望有人能看到我可能會失蹤的東西。當我輸入800到1800之間的代碼時,代碼仍然正常,但是當我輸入600時,它會跳轉到我以非法格式輸入的其他語句。爲什麼我的第一個if語句的工作,但我的其他if語句之後,在沒有工作

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; 
} 
+2

你別的定義不能成功,因爲TIME_START必須小於800和大於1800,這是不可能的。 – MildWolfie

+0

謝謝大家!我會標記答案! – Mofayew

+0

@Mofayew,不,你不能標記所有的人所接受,所以你必須明智地選擇:P – ForceBru

回答

1

你有一個「邏輯錯誤」:使用||代替&&else if。一個數字不可能小於800並且大於1800 同時

+0

'struct Number {bool operator <(int)const {return true; }布爾運算符>(int)const {return true; }} time_start;' –

+0

@LightnessRacesinOrbit,我在談論普通數字,而不是作爲類/結構實現的數據,因爲我相信時間被表示爲一個數字,而不是一個類。 – ForceBru

+0

我在開玩笑。 –

1

else if ((time_start < 800) && (time_start > 1800))

這是不可能的,一個號碼可以小於800,並大於1800年。我假設你的意思是:

else if ((time_start < 800) || (time_start > 1800))

0

當我問這個問題,我意識到我的第二個else if語句可應該是一個或||聲明而不是& &。

0

變化

否則如果((TIME_START < 800)(TIME_START> 1800

否則如果((TIME_START < 800) ||(time_start> 1800

0

您可以將代碼簡化爲this,否則不需要聲明。存儲在係數變量的值,這就是需要之前

// 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;