theGrayFox
theGrayFox

Reputation: 931

C modulos and Remainders

Hey, I'm having the toughest time figuring out how to display this result. Say for example I enter a number such as 59. Based off that number, I get a remaining result of 1 week(s) 2 Day(s) and 5 Hour(s). This is of course assuming one week has 40 hours and 1 day has 7 hours in order to get that output. Any help in the right direction would be helpful. So far I've set it up like so:

scanf("%d %d %d", &totalWeeksWorked, &totalDaysWorked, &totalHoursWorked);

Upvotes: 1

Views: 281

Answers (2)

Fred Nurk
Fred Nurk

Reputation: 14212

#include <stdio.h>

int const HOURS_PER_WEEK = 40;
int const HOURS_PER_DAY = 7;

int main() {
  int total_hours = 59;  // this is the input you get

  int remaining = total_hours;  // 'remaining' is scratch space

  int weeks = remaining / HOURS_PER_WEEK;
  remaining %= HOURS_PER_WEEK;

  int days = remaining / HOURS_PER_DAY;
  remaining %= HOURS_PER_DAY;

  int hours = remaining;

  printf("%d hours = %d weeks, %d days, %d hours\n",
         total_hours, weeks, days, hours);

  return 0;
}

Upvotes: 0

soandos
soandos

Reputation: 5146

This is not the fastest way, but is perhaps the most illustrative:

int numodweeks = input/(7*24);
int numofdays  =input/24;
int numofhours = 24 - (input/24);

Using modulo:

        int numofweeks = input/(7*24);
        int numofdays = (input%numofweeks)/7;
        int numofhours = (input%(numofdays*24));

Then display them how you want.

Upvotes: 2

Related Questions