简化舍入代码 C

  • 本文关键字:代码 舍入 c rounding
  • 更新时间 :
  • 英文 :


我是编码新手,并试图弄清楚如何让代码四舍五入到下一个小时。我能想到的唯一方法(即我被教导的唯一方法)是每小时做一次else if语句。显然,这根本没有效率,我知道可能还有更简单的事情。我得到了一个线索,其中涉及一个数学方程式?

以下是我到目前为止编写的内容:

#include <stdio.h>
int main()
{
//listens for value of "cost"
    float cost;
    printf("How much does this go-kart location charge per hour?n");
    scanf("%f", &cost);
//listens for value of "time"
    float time;
    printf("How many minutes can you spend there?n");
    scanf("%f", &time);
// i have to get it to round time to values of 60 (round up to next hour)
//really overcomplicated lack of knowledge workaround.txt
    if (time < 60 && time > 0){
    time = 1;
   } else if(time > 61 && time < 70){
    time = 2;
   } else if(time > 71 && time < 80){
    time = 3;
   } else if(time > 81 && time < 90){
    time = 4;
   } else if(time > 91 && time < 100){
    time = 5;
   } else if(time > 101 && time < 160){
    time = 6;
   }
//etc etc
float total = cost * time;
printf("Your total will be $%fn", total);
return 0;
}

对于非固定间隔,可以执行以下操作:

int times[] = { 60; 70; 80; 90; 100; 160; INT_MAX }; // INT_MAX is to avoid segfault for bad input
int facts[] = {  1;  2;  3;  4;   5;   6;      -1 }; // -1 is value for bad input
int it = 0;
while(times[it] < time) ++it;
int result = facts[it];

请注意,您的代码没有时间 = 60、70 等的有效结果......您应该检查想要的行为

int hour = time/60;
if(60*hour < time)
  ++hour;
这是

相当基本的数学。

time/60 将四舍五入到给您小时。

因此 ( time/60) + 1 次四舍五入。

如果最长为 6 小时,则只需检查:

hour = time/60 + 1;
if (hour > 6) hour = 6;

当然,我假设时间是一个int.如果是float则可以使用floorceil向上或向下舍入:

hour = floor(time/60 +1);

hour = ceil(time/60);

我认为这还不错

time = (time % 60) ? time / 60 + 1 : time / 60

最新更新