Counting in function

Hello, what is wrong in this function:
1
2
3
4
5
6
7
8
9
10
11
12
13
  void MinusMoney(int a, int b) {
	b -= money2;
	startas1:
	if (b < 0) {
		a--;
		b += 100;
		goto startas1;
	}
	else {
		money1 -= a;
		money2 -= b;
	}
}

money1 and money2 is global variables.
My problem that if i have 7.20(money1 = 7, money2=20) and i try:
MinusMoney(2, 50)
I get result: 5.-10.... why?
There isn't a single thing wrong with it. The function just isn't implementing the subtraction algorithm correctly.
Try to think more carefully about what it is you're trying to do. It looks like you're close to the right idea, but you're not putting the pieces together properly, if that makes sense.
oh... I get it. I was sorely confused earlier. While you can do it that way, its a pain. I would use the direct approach:

void mm(int a, int b)
{
int cents1 = a*100+b;
int cents2 = money1*100+money2;
int dollarresult = (cents2 - cents1)/100;
int cresult = (cents2-cents1)%100;
//do something here with the 2 results.
}


and you still don't really want to use a lot of globals and gotos :)
Last edited on
jonnin your code is working. But maybye someone can explain me what exactly was wrong with my code?
Just do the math:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// money1 ==  7
// money2 == 20
//                  2     50
void MinusMoney(int a, int b)
{
    b -= money2; // b --> 50 - 20 --> 30
startas1:
    if (b < 0) { // all skipped
        a--;
        b += 100;
        goto startas1;
    }
    else {
        money1 -= a; // money1 -->  7 -  2 -->   5
        money2 -= b; // money2 --> 20 - 30 --> -10
    }
}

A different test case will the issue of the logic a bit differently:

You have 60 cents. You take off a whole dollar:
(0, 60) - (1, 0) = (-1, 60)

That answer is technically correct, but one might intuitively expect (0, -40).

An another question is whether you want to posses negative money.
your code does not understand the 2 numbers belong together. 150 -60 is 90. But your code has 100 - 0 and 50-60, and can't "borrow" from the 100 to get the correct answer because the 2 numbers have nothing to tie them together. You have to make this connection somehow.

what I did was convert them back to a common value, let the computer do the math, and pull them back apart. This seems easier to me than trying to handle the split number approach.



Topic archived. No new replies allowed.