为什么在函数中传递参数时会出现算术计算错误

Why do errors in arithmetic calculations when passing argument in function occur?

本文关键字:错误 计算 函数 参数 为什么      更新时间:2023-10-16

下面的代码编译正确,但计算似乎是问题当打印出第一个扣款"提款"时customerBalance是2.07361e(8032.78-244.0=7788.78)?数据成员是私有的,但这似乎不是问题公开的或私人的。我不确定。任何建议都是欢迎非常感谢。

#include <iostream>
#include "BankAccount.hpp"
using namespace std;
BankAccount::BankAccount(string name, string ID, double balance)
{
    customerName = name;
    customerID = ID;
    customerBalance = balance;
}
string BankAccount::getCustomerName()
{
    return customerName;
}
string BankAccount::getCustomerID()
{
    return customerID;
}
double BankAccount::getCustomerBalance()
{
    return customerBalance;
}
void BankAccount::withdraw(double w)
{
    customerBalance = (customerBalance - w);
}
void BankAccount::deposit(double d)
{
    customerBalance = (customerBalance + d);
}
int main()
{
    double customerBalance;
    BankAccount account1("Harry Potter", "K4637", 8032.78);
    account1.withdraw(244.0);
    cout << customerBalance;
    account1.withdraw(3012.58);
    account1.deposit(37.54);
    account1.withdraw(1807.12);
    account1.deposit(500.00);
    double finalBalance = account1.getCustomerBalance();
 }

您在main中声明的cusotmerBalanceBankAccount::customerBalance不同。您从未初始化customerBalance,因此在打印时它有一个未定义的值。