gpt4 book ai didi

c++ - 使用数组的文件输出不正确

转载 作者:行者123 更新时间:2023-11-30 03:04:54 25 4
gpt4 key购买 nike

大家好,我刚刚开始学习我的第一门编程语言,并且刚刚更正了我的代码中的一个错误,结果又留下了另一个错误。值得庆幸的是,这是我需要解决的最后一个问题,但我自己做起来有点麻烦。

程序是读入一个客户编号和每个客户编号相关的费用。然后它会添加财务费用,输出所有费用,汇总所有内容,并以相反的顺序保存每个客户的新余额以及他们的 ID 号以归档。

beginningbalance.dat 看起来像

111
200.00
300.00
50.00
222
300.00
200.00
100.00

和 newbalances.dat 应该看起来像

222
402.00
111
251.00

除了取决于在文件写入循环中放置“count--”的位置,我最终得到了

222
402.00
111
251.00
-858993460
-92559631349317830000000000000000000000000000000000000000000000.00

我不知道我应该怎么做才能摆脱这些额外的值(value)。有什么建议吗?

这是我的代码

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;



int main()
{
int count = 0;
const int size = 100;
double customer_beg_balance, customer_purchases, customer_payments, finance_charge_cost, finance_charge = .01;
int customer_number[size];
double new_balance[size];
double total_beg_balances=0,total_finance_charges=0,total_purchases=0,total_payments=0,total_end_balances=0;


ifstream beginning_balance;
beginning_balance.open("beginningbalance.dat");

while(beginning_balance>>customer_number[count])
{
beginning_balance >> customer_beg_balance;
beginning_balance >> customer_purchases;
beginning_balance >> customer_payments;

finance_charge_cost = customer_beg_balance * finance_charge;

new_balance[count] = customer_beg_balance + finance_charge_cost + customer_purchases - customer_payments;
total_beg_balances+=customer_beg_balance;
total_finance_charges+=finance_charge_cost;
total_purchases+=customer_purchases;
total_payments+=customer_payments;
total_end_balances+=new_balance[count];

cout<<fixed<<setprecision(2)<<setw(8)<<"Cust No "<<"Beg. Bal. "<<"Finance Charge "<<"Purchases "<<"Payments "<<"Ending Bal.\n"
<<customer_number[count]<<" "<<customer_beg_balance<<" "<<finance_charge_cost<<" "<<customer_purchases<<" "<<customer_payments<<" "<<new_balance[count]<<endl;


count++;
}

cout<<"\nTotals "<<total_beg_balances<<" "<<total_finance_charges<<" "<<total_purchases<<" "<<total_payments<<" "<<total_end_balances<<endl;

ofstream new_balance_file;
new_balance_file.open("NewBalance.dat");

while(count >= 0)
{
count--;
new_balance_file <<customer_number[count]<<endl;
new_balance_file<< fixed<<setprecision(2)<<new_balance[count]<<endl;

}


new_balance_file.close();


system("pause");
return 0;
}

最佳答案

你的条件不对

 while(count >= 0)
{
count--;
new_balance_file <<customer_number[count]<<endl;
new_balance_file<< fixed<<setprecision(2)<<new_balance[count]<<endl;

}

应该是 count > 0 而不是 count >= 0

这样 count 将遍历值 n, n-1, ... 1 并且因为您在 while 语句的开头递减它,您将在其中操作的值您的循环将是 n-1, n-2.... 0,正是您所需要的。

顺便说一句,如果你的类(class)已经涵盖了for循环并且你被允许使用它,那么它更适合,像这样

for(int i = count - 1; i >= 0; --i)
{
use i instead of count here.
}

希望对你有所帮助,祝你学业顺利!

关于c++ - 使用数组的文件输出不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8234477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com