I'm trying to write some c code (objective c) which will take a bank account balance and a desired balance from the user and produce a value which I can add or subtract from the current balance to achieve the desired balance.
I think I'm made things overcomplicated, heres what I have...
//get desired amount to variable dblDesiredBalance
//get balance from database to variable balFromDB
double addAmount = fabs(balFromDB) + fabs(dblDesiredBalance);
double minusAmount = fabs(dblDesiredBalance) - fabs(balFromDB);
// create amount to add to db
if (dblDesiredBalance < 0 ) {
if (balFromDB < 0 ) {
dblCommitToDB = balFromDB - minusAmount;
} else {
dblCommitToDB = balFromDB - addAmount;
}
} else {
if (balFromDB < 0 ) {
dblCom开发者_如何学编程mitToDB = balFromDB + addAmount;
} else {
dblCommitToDB = balFromDB + minusAmount;
}
}
// update db with dblCommitToDB
Can anyone help me ?
Why not start from simple algebra:
current_balance + delta = desired_balance
and then solve for delta:
delta = desired_balance - current_balance
This works independent of signs - you know algebraic rules and all.
精彩评论