2017-05-14 82 views
1

我對C++相當陌生,我被賦予了一個相當基本的程序,用戶可以用它來購買門票,但我在計算中遇到了一些問題。計算沒有正確完成

這是我的代碼到目前爲止。

#include <iostream> 

using namespace std; 

int main() 
{ 
double type_ticket, num_tickets, price1, price2, price3, total_price, decision; 

cout << "Welcome to the ticket kiosk."; 
cout << "\n"; 
cout << "\n"; 
cout << "1. VVIP - RM 200"; 
cout << "\n"; 
cout << "2. VIP - RM 150"; 
cout << "\n"; 
cout << "3. Normal - RM 100" << endl; 
cout << "\n"; 


do 
{ 
cout << "Please select the category of ticket you would like to purchase: "; 
cin >> type_ticket; 
cout << "\n"; 


if (type_ticket == 1) 
{ 
cout << "How many would you like: "; 
cin >> num_tickets; 
cout << "\n"; 
price1 = num_tickets * 200; 
cout << "The price is: RM " << price1 << endl; 
cout << "\n"; 
cout << "\n"; 
cout << "1. YES" << endl; 
cout << "2. NO" << endl; 
cout << "\n"; 
cout << "Would you like to continue purchasing more tickets: "; 
cin >> decision; 
cout << "\n"; 
} 


else if (type_ticket == 2) 
{ 
cout << "How many would you like: "; 
cin >> num_tickets; 
cout << "\n"; 
price2 = num_tickets * 150; 
cout << "The price is: RM " << price2 << endl; 
cout << "\n"; 
cout << "\n"; 
cout << "1. YES" << endl; 
cout << "2. NO" << endl; 
cout << "\n"; 
cout << "Would you like to continue purchasing more tickets: "; 
cin >> decision; 
cout << "\n"; 
} 


else if (type_ticket == 3) 
{ 
cout << "How many would you like: "; 
cin >> num_tickets; 
cout << "\n"; 
price3 = num_tickets * 100; 
cout << "The price is: RM " << price3 << endl; 
cout << "\n"; 
cout << "\n"; 
cout << "1. YES" << endl; 
cout << "2. NO" << endl; 
cout << "\n"; 
cout << "Would you like to continue purchasing more tickets: "; 
cin >> decision; 
cout << "\n"; 
} 


else 
{ 
cout << "You have entered an invalid input, please try again. " << endl; 
cout << "\n"; 
} 


} 
while (decision == 1); 

total_price = price1 + price2 + price3; 
cout << "The grand total is: RM " << total_price << endl; 
cout << "\n"; 
cout << "Thank you for using this service today, we hope you enjoy the show." << endl; 
cout << "\n"; 

} 

,我遇到的問題是,當用戶從購買VVIP和/或VIP門票,爲TOTAL_PRICE計算沒有被這樣做的權利。但是,如果輸入價格3,則計算工作正常。

用戶購買vvip和/或vip =計算不正確。 用戶購買正常和vvip和/或vip =計算正確。

任何幫助將非常感激。這個代碼還沒有完成,但現在,這就是我所擁有的。

+0

請解釋一下什麼是「做得不對」的含義。什麼是投入,產出,預期產出? – user463035818

+0

由於您是SO的新用戶,請欣賞其他用戶的時間,所以您至少需要:在您的問題中正確設置代碼的格式,解釋具體問題('無法正常工作'並非適當的描述)你的輸入和輸出。 – Alex

+0

我剛剛運行您的程序,並從您提供的它似乎工作正常。要求3類2票,總成本是450.請詳細瞭解這不起作用。 –

回答

2

你似乎無法計算之前初始化priceN(其中N1, 2, 3一個變量):在只有一種類型的票的情況下

total_price = price1 + price2 + price3; 

,所以結果是不可預知的,因爲變量包含垃圾。

你應該這樣開始:

double price1 = 0; 
double price2 = 0; 
double price3 = 0; 
+0

這工作,謝謝我真的很感激它,我確實試圖做到這一點,但沒有宣佈它是一個雙重的三倍。 double type_ticket,num_tickets,price1 = 0,price2 = 0,price3 = 0,total_price,decision;我假設這樣做是行不通的? –

+0

它不是聲明,它是初始化是這裏的關鍵。多行聲明是一種風格選擇,但重點是沒有默認初始化爲0,所以你必須自己做。當然,它會 –

+0

所以,如果我在if else部分添加了priceN = 0,例如在這兩個代碼之間,請參見 cout <<「\ n」; price3 = num_tickets * 100;它會繼續工作嗎? 例如 cout <<「\ n」; price3 = 0; price3 = num_tickets * 100; –