c - 我调用这个函数错了吗?

标签 c function structure

我正在编写一个程序来计算两个给定时间之间耗时。

出于某种原因,我收到错误:在我的主要函数之前,我的 elapsedTime 函数原型(prototype)需要标识符或“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;
}

最佳答案

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

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

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

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

您还需要将函数的返回值分配给某些东西:

struct time differ = elapsedTime(t1, t2);

有了这个工作,你在做差异时“借用”的逻辑是倒退的:

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;

关于c - 我调用这个函数错了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38511912/

相关文章:

swift - 如果连接到快速查看 Controller ,选择器将不起作用

c++ - 静态成员函数无法访问类的 protected 成员

c - 管道结构错误

c - 具有常量成员的结构的内存分配

python - C 中是否有与 Python 中的 raw_input 功能相同的函数?

javascript - JS基本功能不起作用

c - 套接字中的填充结构

c++ - 如何将类成员函数的返回类型设置为私有(private)结构的对象

c - strtok 覆盖我的变量

c - 获取与预期不同的值在循环中运行。为什么?