我称这个功能错了吗?

glo*_*pit 0 c structure function

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

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

我试过在程序中移动它,如果在声明了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;
}
Run Code Online (Sandbox Code Playgroud)

dbu*_*ush 6

您的函数未正确定义返回类型:

struct elapsedTime(struct time t1, struct time t2);
Run Code Online (Sandbox Code Playgroud)

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

struct time elapsedTime(struct time t1, struct time t2);
Run Code Online (Sandbox Code Playgroud)

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

struct time differ = elapsedTime(t1, t2);
Run Code Online (Sandbox Code Playgroud)

通过这种工作,你在做差异时"借用"的逻辑是倒退的:

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;
}
Run Code Online (Sandbox Code Playgroud)

如果是,如果t1是之后t2,小时将是负数.如果您认为这意味着结束时间是第二天,则添加24到小时:

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

differ.hours= t2.hours - t1.hours;
Run Code Online (Sandbox Code Playgroud)