compounding / while loops

168 Views Asked by At
#include <stdio.h>

int main(void)
{
  int days, hours, mins;
  float a, b, c, total, temp, tempA, tempB;

  a = 3.56;
  b = 12.50;
  c = 9.23;
  total = a+b+c;
  days = total / 24;

  temp = total/24 - days;

  hours = temp * 24;

  tempA = temp*24 - hours;

  mins = tempA*60;

  while (hours >= 24)
    {
      hours= hours-24;
      days +=1;
    }
  while  ( mins >= 60)
    {
      mins=mins-60;
      hours +=1;
    }
  printf("days:%d\n", days);
  printf("hours:%d\n", hours);
  printf("mins:%d\n", mins);


  return 0;
}

I wanted to convert decimal hours to real time and I can do it fine but I wanted to increase days hours if the hours is beyond 24 and if mins is beyond 60mins. the while loop does subtract and it does print out the new value but the hours / days aren't getting compounded. It was 1 day 1 hour 77mins I wanted it to read 1 day 2 hours 17mins but I'm getting 1 day 1 hour 17 mins.

5

There are 5 best solutions below

0
AProgrammer On BEST ANSWER

Running your program I'm getting:

days:1
hours:1
mins:17

and that's what I expect considering that total should be 25.29.

0
Andy On

It works fine, your math is just a little off. (= (+ 3.56 12.50 9.23) 25.29), not 26.29.

0
user470379 On

Using the modulus operator will make your life much easier: it will give the remainder of a division.

int total;

/* a=; b=; c=; assignments */

total = a+b+c;
mins = total % 60;
total /= 60;
hours = total % 24;
days = total / 24;
0
Matt Curtis On

Instead of a while loop you can use division:

days += hours / 24
hours %= 24

Also, do your minutes-to-hours stuff before your hours-to-days stuff.

0
bits On

Here is a simpler implementation of what you are trying to do:

void TimeFix(int &days, int &hours, int &mins)
{
    hours += mins/60;
    mins %= 60;
    days += hours/24;
    hours %= 24;
}