我称这个功能错了吗?

时间:2016-07-21 18:35:20

标签: c function structure

我正在编写一个程序来计算两次给定时间之间的经过时间。

出于某种原因,我收到错误:预期标识符或' C'关于我的main函数之前的elapsedTime函数原型。

我试过在程序中移动它,如果我在声明了t1和t2之后找到了它,它就不会有所作为。问题是什么?

谢谢

#include <stdio.h>

struct time
{
  int seconds;
  int minutes;
  int hours;
};

struct elapsedTime(struct time t1, struct time t2);

int main(void)
{

    struct time t1, t2;

    printf("Enter start time: \n");
    printf("Enter hours, minutes and seconds respectively: ");
    scanf("%d:%d:%d", &t1.hours, &t1.minutes, &t1.seconds);

    printf("Enter stop time: \n");
    printf("Enter hours, minutes and seconds respectively: ");
    scanf("%d:%d:%d", &t2.hours, &t2.minutes, &t2.seconds);

    elapsedTime(t1, t2);

    printf("\nTIME DIFFERENCE: %d:%d:%d -> ", t1.hours, t1.minutes, t1.seconds);
    printf("%d:%d:%d ", t2.hours, t2.minutes, t2.seconds);
    printf("= %d:%d:%d\n", differ.hours, differ.minutes, differ.seconds);

    return 0;
}

struct elapsedTime(struct time t1, struct time t2)
{
    struct time differ;

    if(t2.seconds > t1.seconds)
    {
        --t1.minutes;
        t1.seconds += 60;
    }

    differ.seconds = t2.seconds - t1.seconds;

    if(t2.minutes > t1.minutes)
    {
        --t1.hours;
        t1.minutes += 60;
    }

    differ.minutes = t2.minutes - t1.minutes;
    differ.hours = t2.hours - t1.hours;

    return differ;
}

1 个答案:

答案 0 :(得分:6)

您的功能没有正确定义返回类型:

struct elapsedTime(struct time t1, struct time t2);

struct本身不足以定义返回类型。您还需要结构名称:

struct time elapsedTime(struct time t1, struct time t2);

您还需要将函数的返回值赋值为:

struct time differ = elapsedTime(t1, t2);

有了这个工作,你的逻辑就是&#34;借用&#34;当做差异是倒退时:

if(t1.seconds > t2.seconds)     // switched condition
{
    --t2.minutes;               // modify t2 instead of t1
    t2.seconds += 60;
}

differ.seconds = t2.seconds - t1.seconds;

if(t1.minutes > t2.minutes)     // switched condition
{
    --t2.hours;                 // modify t2 instead of t1
    t2.minutes += 60;
}

原样,如果t1t2之后,则小时为负数。如果您认为这意味着结束时间是第二天,则添加24到小时:

if(t1.hours > t2.hours)
{
    t2.hours+= 24;
}

differ.hours= t2.hours - t1.hours;