Home > Back-end >  How add two times in c?
How add two times in c?

Time:09-02

I am trying to add two times like 20:30 1:40 = 22h 10m. I'm having a problem with the remainder after the dot

#include <stdio.h>

float walking (float start,float duration);

int main() {
  printf ("finish = %.2f", walking(20.30, 1.40));
  return 0;
}

float walking(float start, float duration) {
  int finMinuites = (int)(start * 100) % 100   (int)(duration * 100) % 100;
  int finHours = (start * 100) / 100   (duration * 100) / 100;

  if (finMinuites >= 60) {
    finMinuites -= 60;
    finHours  ;
  }

  if (finHours >= 24)
    finHours -= 24;

    return finHours   finMinuites / 100;
  }

CodePudding user response:

floor and fmod can be used to extract the whole and fractional parts of a double.
Link with -lm.

#include <stdio.h>
#include <math.h>

double walking ( double start, double duration) {
    double fraction = 0.0;
    double whole = 0.0;

    whole = floor ( start);
    fraction = fmod ( start, whole);
    start = whole;

    whole = floor ( duration);
    start  = whole;
    fraction  = fmod ( duration, whole);
    fraction /= .60;

    whole = floor ( fraction);
    start  = whole;
    fraction -= whole;
    fraction *= .60;
    start  = fraction;
    return start;
}

int main ( void) {

    printf ( "%.2f\n", walking ( 20.3, 1.4));

    return 0;
}

CodePudding user response:

If you really want to store time in a float then here is a solution:

#include<stdio.h>
#include<math.h>

float walking(float start,float duration);
int main() {
    printf("finish = %.2f",walking(20.30, 1.40));
    return 0;
}
int toMinutes(float time){
    int t = (int)round((time*100));
    int hours = t/100;
    int min = t - hours * 100;
    return hours*60 min;
}
float toFloat(int minutes){
    int hours = minutes/60;
    int min = minutes - hours * 60;
    float t = hours * 100;
    t  = min;
    t /= 100;
    return t;
}
float walking(float start,float duration){
    int mins = toMinutes(start)   toMinutes(duration);
    int day = 24*60;
    while(mins > day){
        mins -= day;
    }

    return toFloat(mins);
}

But I would suggest storing the minutes as an int instead.

CodePudding user response:

Staying in the realm of floating point:

#include <math.h>

double walking( double bgn, double dur ) {
    double bgnHrs = floor( bgn ); // preserve hours
    bgn = (bgn - bgnHrs) * 100.0/60.0; // scale minutes

    double durHrs = floor( dur ); // preserve hours
    dur = (dur - durHrs) * 100.0/60.0; // scale minutes

    double resHrs = floor( bgnHrs   durHrs ); // add hrs

    double resMin = bgn   dur; // add min

    if(  resMin >= 1.0 ) // overflow min?
        resHrs  = 1.0, resMin -= 1.0;

    if( resHrs >= 24.0 ) // past midnight?
        resHrs -= 24.0;

    resMin *= 60.0/100.0; // scale minutes

    return resHrs   resMin;
}

int main() {

    printf ( "finish = %.2f", walking( 20.30, 1.40 ) );

    return 0;
}
  • Related