C模数和余数

时间:2011-05-22 03:38:03

标签: c modulo

嘿,我有最艰难的时间来弄清楚如何显示这个结果。例如,我输入一个59之类的数字。根据该数字,我得到1周(s)2天(s)和5小时(s)的剩余结果。这当然是假设一周有40小时而1天有7小时以获得该输出。任何正确方向的帮助都会有所帮助。到目前为止,我已经这样设置了:

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

2 个答案:

答案 0 :(得分:2)

这不是最快的方法,但可能是最具说明性的方式:

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

使用modulo:

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

然后按照你想要的方式显示它们。

答案 1 :(得分:0)

#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;
}