开发者

Coding a maths problem to find the difference between two numbers which could be negative

开发者 https://www.devze.com 2023-01-23 06:23 出处:网络
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 ac

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消