1
//import library
#include <stdio.h>
#include <stdlib.h>

//declare variable structure
struct time{
    int hour;
    int min;
    int sec;
}startTime, endTime, different, elapsed;

//mould struct and compute elapsedTime
struct time elapsedTime(struct time start, struct time end){

    int secondStart, secondEnd, secondDif;

    secondEnd = end.hour * 60 * 60 + end.min * 60 + end.sec;
    secondStart = start.hour * 60 * 60 + start.min * 60 + start.sec;
    if (secondEnd>secondStart)
        secondDif = secondEnd - secondStart;
    else
        secondDif = secondStart - secondEnd;

    different.hour = secondDif / 60 / 60;
    different.min = secondDif / 60;

    return different;
}

//main function
void main(){
    printf("Enter start time (Hour Minute Second) using 24 hours system : ");
    scanf("%d %d %d", startTime.hour, startTime.min, startTime.sec);

    printf("Enter end time (Hour Minute Second) using 24 hours system : ");
    scanf("%d %d %d", endTime.hour, endTime.min, endTime.sec);

    elapsed = elapsedTime(startTime, endTime);
}

有人可以帮我检查并运行代码以检查它是否工作吗?

4

2 回答 2

1

你在 main 函数中有一个错误,你应该在 scanf 中使用int *而不是int所以你必须添加&,你可以看到如下:

//main function
void main(){
    printf("Enter start time (Hour Minute Second) using 24 hours system : ");
    scanf("%d %d %d", &startTime.hour, &startTime.min, &startTime.sec);

    printf("Enter end time (Hour Minute Second) using 24 hours system : ");
    scanf("%d %d %d", &endTime.hour, &endTime.min, &endTime.sec);

    elapsed = elapsedTime(startTime, endTime);
}
于 2015-12-30T10:10:05.450 回答
0

我假设您想要计算different.sec,所以我认为不同时间的正确计算是:

secPerHr = 60 * 60;
secPerMin = 60;

if (secondDif >= secPerHr) {
different.hour = secondDif / secPerHr;
secondDif -= different.hour * secPerHr;
}
if (secondDif >= secPerMin) {
different.min = secondDif / secPerMin;
secondDif -= different.min * secPerMin;
}
different.sec = secondDif;

此外,出于测试目的,您可能希望在主函数中显示结果。

于 2015-12-30T11:55:33.153 回答