我的代码有问题,每次我用答案'y'循环它(是)它循环到无穷大?
我正在尝试制作一个贷款计算器,每次用户完成交易计算并希望重置,如果他输入值'y',则进行另一次计算,如果他输入'n',节目将结束。
到目前为止,这是我的代码:
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
char ans = 'y';
do {
string name;
int Months;
int n;
double LoanAmount, Rate, MonthlyInterest, TotalLoanAmount, MonthlyAmortization, OutstandingBalance;
cout << fixed << showpoint;
cout << "Enter Name of Borrower: ";
getline(cin, name);
cout << "Enter Loan Amount: ";
cin >> LoanAmount;
cout << "Enter Number of Months to Pay: ";
cin >> Months;
cout << "Enter Interest Rate in Percent(%): ";
cin >> Rate;
cout << setprecision(2);
MonthlyInterest = LoanAmount * Rate;
TotalLoanAmount = LoanAmount + (MonthlyInterest * Months);
cout << "Monthly Interest: " << MonthlyInterest << endl
<< "Total Loan Amount with interest: " << TotalLoanAmount << endl;
cout << setw(100)
<< "\n\tSUMMARY OF OUTSTANDING INSTALLMENT" << endl
<< "\tName of Borrower: " << name
<< "\n\nMonth\t\tMonthly Amortization\t\tOutstanding Balance"
<< "\n";
for(n = 1; n <= Months; n++) {
MonthlyAmortization = TotalLoanAmount / Months;
OutstandingBalance = TotalLoanAmount - MonthlyAmortization;
cout << n << "\t\t" << MonthlyAmortization << "\t\t\t" << n - 1 << OutstandingBalance << endl;
}
cout << "\nEnd of Transaction";
cout << "Do you want to compute another transaction?[y/n]?" << endl;
cin >> ans;
}
while(ans == 'y');
}
答案 0 :(得分:0)
在你的cin&gt;&gt; ans之后,添加以下两行:
cin.clear();
cin.sync();
这通常解决了我用cin获得的许多无限循环问题。
另外,我建议不要将ans初始化为&#39; y&#39;当你宣布它。我不认为这会给你带来麻烦,但这不是一件麻烦事。
答案 1 :(得分:0)
您似乎期望按y并输入以仅注册为'y'。如果您只想获得一个字符的输入,请查看std::cin.get(char)