我正在製作一個銀行程序,要求輸入諸如帳號,姓名和餘額等幾項信息。它應該顯示10個月內均勻支付的餘額。但由於某種原因,當我輸入一個名稱時,輸出之間的空格將無限循環。我認爲使用getline(cin,name)會解決問題,但它只會產生更多問題。輸入一些數字也會導致無限循環。爲什麼我的輸出無限循環?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void displayColumnTitle() {
cout << "MONTH BALANCE DUE" << endl;
}
float calculateBalanceDue(float balanceDue, float paymentAmt) {
balanceDue = balanceDue - paymentAmt;
return balanceDue;
}
void displayBalance(int month, float balanceDue) {
cout << left << setw(10) << month << right << setw(7)
<< setiosflags(ios::fixed) << setprecision(2) << balanceDue << endl;
}
int main() {
float accountNumber = 0;
float balanceDue, paymentAmt;
int month = 1;
string name;
while (accountNumber != -1)
{
cout << "Enter Account Number(-1 to terminate the input):" << endl;
cin >> accountNumber;
if (accountNumber == -1) {
break;
}
cout << "Enter name: ";
getline(cin, name);
cout << "\nEnter balance due:" << endl;
cin >> balanceDue;
cout << "\nAccount Number: " << accountNumber << endl
<< "Name: " << name << endl << endl;
displayColumnTitle();
paymentAmt = balanceDue * .10;
while (balanceDue != 0) {
balanceDue = calculateBalanceDue(balanceDue, paymentAmt);
displayBalance(month, balanceDue);
month++;
}
}
return 0;
}
對於凌亂的代碼我很抱歉,因爲我是初學者。
您確定'accountNumber'應該是浮點變量嗎?沒有什麼意義。 –
另外,由於浮點值在計算機上的工作方式,幾乎所有對浮點值的操作都會導致四捨五入錯誤,這會增加您執行的更多操作。這意味着您可能會將* close *設置爲0來表示「balanceDue」,但不完全爲零。請閱讀[「浮點數學是否被破壞?」](http://stackoverflow.com/questions/588004/is-floating-point-math-broken)。 –
哎呀你是對的它應該是int – blionzion