2017-02-09 23 views
-1

這是我爲我在Bjarne Stroustrup的編程原理和C++書中編寫的解決方案所做的嘗試。不幸的是,我寫信給從輸入的硬幣總金額不符合我的願望!C++基本轉換,然後添加用戶輸入

一個簡單的答案,我會非常感激,但如果任何人也有時間可以幫助我介紹一些基本的錯誤檢查?

我希望它的工作,需要用戶輸入後會的方式(例如有多少20P的,你呢?),以檢查是否用戶輸入的int。如果沒有,提供一個微妙的錯誤信息,並有機會重複相同的問題,而不是停止程序或從一開始就開始程序!

#include "../../std_lib_facilities.h" 

int main() { 
int one, ten, twenty, fifty, one_pound, two_pound; 
double amount; 
amount = (one * 0.01) + (ten * 0.1) + (twenty * 0.2) + (fifty * 0.5) + one_pound + (two_pound * 2); 
cout << "Welcome to the change counter app!\nHow many 1p's do you have?\n"; 
cin >> one; 
cout << "How many 10p's do you have?\n"; 
cin >> ten; 
cout << "How many 20p's do you have?\n"; 
cin >> twenty; 
cout << "How many 50p's do you have?\n"; 
cin >> fifty; 
cout << "How many £1 coin's do you have?\n"; 
cin >> one_pound; 
cout << "How many £2 coin's do you have?\n"; 
cin >> two_pound; 
cout << "You have: " << one << " 1p coins!\n" 
    << "You have: " << ten << " 2p coins!\n" 
    << "You have: " << twenty << " 20p coins!\n" 
    << "You have: " << fifty << " 50p coins!\n" 
    << "You have: " << one_pound << " £1 coins!\n" 
    << "You have: " << two_pound << " £2 coins!\n" 
    << "The total amount of money you have is: " << amount << "\n"; 
} 
+0

舉動'金額=(一個* 0.01)+(....'後'最後等cin'前年'cout' – Garf365

+0

歡迎堆棧溢出。我建議你看一看一輪的幫助中心,特別是關於「如何提出一個好問題」的部分。 –

回答

0

你有問題:

首先是在沒有循環,代碼從上到下運行。這意味着你在輸入之前計算amount

的第二個問題是,當你計算amount(目前,在錯誤的地方),你使用它們初始化前的變量oneten。未初始化的局部變量將具有未定義的值,並且使用它們將導致未定義的行爲

簡單的解決這兩個問題是之前的amount計算移動到後您已經閱讀輸入,但你寫的輸出。

0

問題是你正在計算amount與未初始化的變量。在所有變量初始化之後,您需要計算amount。您的變量僅在所有cin語句執行後才初始化。

你需要最後cin語句之後移動

amount = (one * 0.01) + (ten * 0.1) + (twenty * 0.2) + (fifty * 0.5) + one_pound + 
(two_pound * 2); 

int main() { 
int one, ten, twenty, fifty, one_pound, two_pound; 
double amount; 

cout << "Welcome to the change counter app!\nHow many 1p's do you have?\n"; 
cin >> one; 
cout << "How many 10p's do you have?\n"; 
cin >> ten; 
cout << "How many 20p's do you have?\n"; 
cin >> twenty; 
cout << "How many 50p's do you have?\n"; 
cin >> fifty; 
cout << "How many £1 coin's do you have?\n"; 
cin >> one_pound; 
cout << "How many £2 coin's do you have?\n"; 
cin >> two_pound; 

amount = (one * 0.01) + (ten * 0.1) + (twenty * 0.2) + (fifty * 0.5) + one_pound + (two_pound * 2); 
cout << "You have: " << one << " 1p coins!\n" 
    << "You have: " << ten << " 2p coins!\n" 
    << "You have: " << twenty << " 20p coins!\n" 
    << "You have: " << fifty << " 50p coins!\n" 
    << "You have: " << one_pound << " £1 coins!\n" 
    << "You have: " << two_pound << " £2 coins!\n" 
    << "The total amount of money you have is: " << amount << "\n"; 
} 
相關問題