Home > Software engineering >  to choose condition for if-statement
to choose condition for if-statement

Time:11-08

I want to make changes to an inventory balance. By simple logic if I input a number > 0 it should add and subtract if the number is < 0 subtract. So far it works fine.

Now to the issue. If the number that user types is less than inventory balance itself the program should set the value of inventory balance to 0.

For example if the invetory balance is 17 and we type number -18 it should be 0 and not -1.

This is my code so far.

printf("Increase or decrease by: ");
scanf("%d", &n);

if(n >= 0){
    a[i].inventory = a[i].inventory n;
}else{
    a[i].inventory = a[i].inventory n;   //  - = -
    if(n < a[i].inventory){
        a[i].inventory = a[i].inventory- a[i].inventory;
    }

I tried adding the last if-statement, but considering the "bad" logic of if condition, it does not work. bad logic: if inventory is 17 and I want to subtract 2, it will always be less than a[i].inventory and it will jump over else and run the last if-statement.

CodePudding user response:

You are over-complicating a simple task.

a[i].inventory  = n; /* n can be negative too. */

if (a[i].inventory < 0)
    a[i].inventory = 0;

CodePudding user response:

EDIT: love c, suddnely it does not work. brb

I solved it this way:

  printf("increase or decrease by: ");
        scanf("%d", &n);
        
        if(n >= 0 || n < 0){
        a[i].inventory = a[i].inventory n;
        }
        
        if(n < a[i].inventory &&  abs(n) > a[i].inventory){
            a[i].inventory = a[i].inventory- a[i].inventory;
        }
       
    }

thanks for the hint!

  • Related