0

I'm doing my c homework..... :( using a trinomial operator(?) _oo? oo : oo

#include <stdio.h>

int main()
{
    int time1, time2, gap;
    int hour, minute;

    setvbuf(stdout, NULL, _IONBF, 0);
    setvbuf(stdout, NULL, _IONBF, 0);

    printf("Enter first time: \n");
    scanf("%d", &time1);

    printf("Enter second time: \n");
    scanf("%d", &time2);

    gap = time2 - time1;

    gap > 0 ? hour = gap/100 : hour = (2400 - gap)/100;
    gap > 0 ? minute = gap%100 : minute = (2400 - gap)%100;

    print("The gap of these times: %d hours, %d minutes", hour, minute);

}

gap > 0 ? gap/100 = hour : (2400 - gap)/100 = hour;

gap > 0 ? minute = gap%100 : minute = (2400 - gap)%100;

These two sentences are error(lvalue required as left operand of assignment)

The result I want

Enter first time: 1925

Enter second time: 2358

The gap of these times: 4 hours, 33 minutes

OR

Enter first time: 1540

Enter second time: 1630

The gap of these times: 0 hours, 50 minutes

OR

Enter first time: 0730

Enter second time: 0720

The gap of these times: 23 hours, 50 minutes

5

2 Answers 2

4

Try instead:

 hour   = (gap > 0) ? gap/100 : (2400 - gap)/100;
 minute = (gap > 0) ? gap%100 : (2400 - gap)%100;
1

Since both conditional expressions evaluate the same condition, it would be cleaner to combine assignments in an if statement:

if (gap > 0) {
    hour = gap/100;
    minute = gap%100;
} else {
    hour = (2400 - gap)/100;
    minute = (2400 - gap)%100;
}

You could further simplify this by adding a new variable:

int numerator = gap > 0 ? gap : 2400-gap;
hour = numerator/100;
minute = numerator%100;

Not the answer you're looking for? Browse other questions tagged or ask your own question.