将整数转换为分钟

时间:2014-02-28 13:44:03

标签: c time

我是C编程的新手,但在Java方面经验丰富。我正在创建一个简单的控制台应用程序来计算两个选定值之间的时间我将所选的值存储在这样的int数组中:

static int timeVals[] = {748,800,815,830,845,914,929,942,953,1001,1010,1026,1034,1042,1048};

我正在调用方法diff来计算值之间的时间:

int diff (int start, int slut) {
/* slut means end in danish. not using rude words, but I am danish */
int minutes = 0;
int time = 0;
double hest;
hest = (100/60);
printf("hest = %f", hest);
if(timeVals[start] > timeVals[slut])
{
    minutes = timeVals[start] - timeVals[slut];
    /* printing hest to see what the value is */
    printf("t = %f",hest);
    time = minutes * (100/60);
    printf("minut diff: %d\n", time);
}
else
{
    minutes = timeVals[slut] - timeVals[start];
    tiem = time + (minutes * (100/60));
}

return time;
}

奇怪的是,当我打印出hest值时,我得到1.000000,我的意思是不对...我已经在这几个小时里一直在努力,我找不到问题..也许我对数学很不满意:P

希望你能帮助我

3 个答案:

答案 0 :(得分:1)

问题是

hest = (100/60)

此结果将为1,因为100/60 = 1.6666 ....,但这是整数除法,因此您将丢失小数,因此hest = 1.使用

hest = (100.0 / 60.0)

相同

time = minutes * (100/60);

已更改为

time = minutes * (100.0 / 60.0);

在这种情况下,您将丢失小数,因为time是一个int。

如果速度有问题,有些人会建议您执行所有integer calculations并将所有商品以1/100秒的速度存储为整数(即​​以1/100秒为单位的60分钟= 60分钟* 60秒* 100)

编辑:只是为了澄清,该链接适用于C ++,但适用相同的原则。但是在大多数基于x86的系统上,这并不像功耗有限的嵌入式系统那么大。这是讨论此问题的another link

答案 1 :(得分:1)

以下声明是NOP

time = minutes * (100/60);

(100 / 60) == 1因为100和60是整数。你必须写下这个:

time = (minutes * 100) / 60;

例如,如果minutes == 123时间计算为(123 * 100) / 6012300 / 60205

答案 2 :(得分:0)

如上所述,您正在混合浮点和整数运算。除以两个整数后,结果为整数,但是您尝试将该结果打印为float。您可以考虑使用模数运算符(%)并计算商和余数

int // you might want to return float, since you are comingling int and float for time
diff (int start, int slut)
{
    /* slut means end in danish. not using rude words, but I am danish */
    int minutes = 0, seconds = 0, diff;
    int time = 0;
    double hest = (100.0) / (60.0); //here
    printf("hest = %f", hest);
    if(timeVals[start] > timeVals[slut])
    {
        diff = timeVals[start] - timeVals[slut];
        time = diff * (100.0/60.0);
        minutes = diff/60;
        seconds = diff%60; //modulus (remainder after division by 60
    }
    else
    {
        diff = timeVals[slut] - timeVals[start];
        time = time + diff * (100.0/60.0);
        minutes = diff/60;
        seconds = diff%60; //modulus (remainder after division by 60
    }
        /* printing hest to see what the value is */
        printf("t = %f",hest);
        printf("minut:seconds %d:%02d\n", minutes, seconds );
        printf("minut diff: %d\n", time);

    return time;
}