C++代码无法向KirklandLabResults.txt文件输出内容问题求助
C++ 无法向指定文本文件输出内容的问题解决
核心问题汇总
- 文件名不匹配:你预期的输出文件是
KirklandLabResults.txt,但代码里output.open()打开的是Kirklandlab4results.txt,文件名拼写、大小写均不一致,自然不会写入你指定的目标文件。 - 变量输出顺序错误:所有计算相关变量都是先输出再赋值,比如
monthlyPayment先输出初始值0,再做计算,输出内容都是无效初始值,和写入文件功能本身无关。 - 月供计算公式错误:等额本息月供的正确公式是
月还款额 = 贷款本金 * 月利率 * (1+月利率)^还款期数 / [(1+月利率)^还款期数 - 1],你代码里的公式分子分母都误用了loanAmount+interestRate,会导致计算结果完全错误。 - 输入文件路径问题:如果
Lab4Data.txt不在程序运行的工作目录下,输入流读取失败,后续所有写入操作的源数据都是空值,也会导致输出文件内容异常。 - 调试建议:打开文件后增加有效性判断,避免文件打开失败无感知。
修正后完整代码
#include <iostream> #include <fstream> #include <string> #include <iomanip> #include <cmath> using namespace std; int main() { ifstream input; ofstream output; string fName, lName; double loanAmount, numberOfPayments; double interestRate = 0; double monthlyPayment = 0; double totalPayed = 0; double interestAmount = 0; // 输入文件打开校验 input.open("Lab4Data.txt"); if (!input.is_open()) { cout << "输入文件Lab4Data.txt打开失败,请检查文件路径" << endl; return 1; } // 修正为目标文件名,增加打开校验 output.open("KirklandLabResults.txt"); if (!output.is_open()) { cout << "输出文件打开失败,请检查权限和路径" << endl; input.close(); return 1; } input >> fName >> lName; output << "Name:" << fName << " " << lName << endl; input >> loanAmount; output << "Loan Amount:" << loanAmount << endl; input >> interestRate; output << "Annual Intrest Rate:" << interestRate << endl; // 年利率转月利率 interestRate = interestRate / 12 / 100; output << "Monthly Intrest Rate:" << fixed << setprecision(4) << interestRate * 100 << "%" << endl; input >> numberOfPayments; output << "Loan Term (Years):" << numberOfPayments << endl; numberOfPayments = numberOfPayments * 12; output << "Number Of Payments:" << numberOfPayments << endl; // 先计算再输出 double powFactor = pow(1 + interestRate, numberOfPayments); monthlyPayment = loanAmount * interestRate * powFactor / (powFactor - 1); output << "Monthly Payment:" << fixed << setprecision(2) << monthlyPayment << endl; totalPayed = monthlyPayment * numberOfPayments; output << "Total Amount Payed:" << fixed << setprecision(2) << totalPayed << endl; interestAmount = totalPayed - loanAmount; output << "Interest Amount:" << fixed << setprecision(2) << interestAmount << endl; input.close(); output.close(); return 0; }
内容的提问来源于stack exchange,提问作者kirqy
相关产品推荐
相关产品推荐

