复合/while 循环

标签 c compound-assignment

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

我想将十进制小时数转换为实时时间,我可以很好地完成,但如果小时数超过 24 小时并且分钟数超过 60 分钟,我想增加天数小时数。 while 循环确实减去并且它确实打印出新值但是小时/天没有得到复合。 这是 1 天 1 小时 77 分钟 我想让它读 1 天 2 小时 17 分钟 但我得到 1 天 1 小时 17 分钟。

最佳答案

使用取模运算符会让你的生活更轻松:它会给出除法的余数。

int total;

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

total = a+b+c;
mins = total % 60;
total /= 60;
hours = total % 24;
days = total / 24;

关于复合/while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5137723/

相关文章:

C 中的复合运算符 (+=) 和 &&,奇怪的值

c - 什么 *p1 ^= *p2;在c中做

c++ - bool a |= mayRun(); 的右 watch 达式是什么时候?被处决?

javascript - JavaScript 的三元运算符的运算符优先级

c++ - *p++ += 2 定义明确吗?

c - 如何使用文件中的数据填充已分配的二维数组?

c - 将 fgets 与 realloc() 结合使用

c++ - 需要管理一 block 'theoretical'内存的slab

java - 将字符串从 Java 发送到 C(套接字)

c++ - 如何使用 libgit2 从 git 存储库中的 HEAD 获取最后一次提交?