2016-10-15 59 views
1

我無法在用戶輸入的值等於或小於零時正確地嵌套獲取錯誤消息。我不確定它應該去哪裏,或者如果我需要完全做其他事情。任何幫助,將不勝感激。以下是我的代碼。 「一個軟件公司銷售一個零售價爲99美元的軟件包,其數量折扣按照以下方式給出:」10-19 = 20%折扣,20-49 = 30%折扣,50-99 = 40 %折扣,100+ = 50%折扣。 編寫一個程序,要求購買的單位數量並計算購買總成本。 輸入驗證:決定程序應該如何處理的輸入小於0無法正確嵌套我的錯誤消息

#include <iostream> 
#include <iomanip> // needed for setprecision 
#include <stdio.h> 

using namespace std; // need to use cout, cin, etc. 

int main() 
{ 
    double quantity, package = 99.00, initialPrice, discPrice, discount, calcDiscount, percent; // using double here because future multiplication by .2 

    cout << "This program will calculate how much of a discount you may receive,\nbased on how many software packages you buy.\n\n"; 
    cout << "How many software packages do you intend to purchase?\n\n"; 
    cin >> quantity; 

    { 
     if (quantity <= 0) 
      cout << "\nThat is not an acceptable amount. Please re-run the program with a amount greater than zero.\n\n"; 
    } 

    if (quantity >= 10 && quantity <= 19) 
     discount = 0.2, percent = 20; 
    else if (quantity >= 20 && quantity <= 49) 
     discount = 0.3, percent = 30; 
    else if (quantity >= 50 && quantity <= 99) 
     discount = 0.4, percent = 40; 
    else if (quantity >= 100) 
     discount = 0.5, percent = 50; 
    else if (quantity <10 && quantity >=1) 
     discount = 0, percent = 0; 

    { 
     initialPrice = package * quantity; 
     calcDiscount = (discount * package * quantity); 
     discPrice = initialPrice - calcDiscount; 
     cout << "\nThe total price for " << quantity << " software packages, minus a " << percent << "% discount of $"; 
     cout << fixed << showpoint << setprecision(2) << calcDiscount << ","; 
     cout << " is $" << fixed << showpoint << setprecision(2) << discPrice << ".\n\n"; 
    } 

    return 0; 
} 
+0

當有人輸入數量19.5時,你會發生什麼? –

+0

你有一大堆額外的花括號。例如,你的第一個「if」被無故包裹在其中。你最後的'else if'後面還包含了大量的代碼。如果這一切都打算與最後一個「else if」一起發生,那麼您還必須包含該第一行。否則,擺脫那些花括號。 – Gavin

+1

您使用哪本書學習C++? –

回答

1

您的代碼可以固定這樣的:

if (quantity <= 0) 
{ 
    cout << "\nThat is not an acceptable amount. Please re-run the program with a amount greater than zero.\n\n"; 
    return -1; 
} 
else if (quantity < 10) 
    discount = 0, percent = 0; 
else if (quantity < 20) 
    discount = 0.2, percent = 20; 
else if (quantity < 50) 
    discount = 0.3, percent = 30; 
else if (quantity < 100) 
    discount = 0.4, percent = 40; 
else discount = 0.5, percent = 50; 

initialPrice = package * quantity; 
calcDiscount = (discount * package * quantity); 
discPrice = initialPrice - calcDiscount; 
cout << "\nThe total price for " << quantity << " software packages, minus a " << percent << "% discount of $"; 
cout << fixed << showpoint << setprecision(2) << calcDiscount << ","; 
cout << " is $" << fixed << showpoint << setprecision(2) << discPrice << ".\n\n"; 

其他一些小的改動應使代碼的樣子更好 - 它對你

+0

謝謝,這確實有幫助。你對如何處理不完整的數字有想法嗎? (如19.5)。 –

+1

這段代碼會正確處理它們 – Evgeniy