2015-12-30 39 views
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); 
} 

有人可以帮我检查并运行代码以检查它是否工作吗?使用结构的已用时间C程序

+5

你能重新格式化代码吗? – rjdkolb

+0

我的朋友尝试运行,成功执行但未能运行。 – Jonathan

+0

您可以在这里查看源代码:https://www.dropbox.com/s/watwdp7b7vmjbb8/elapsed.c?dl=0 – Jonathan

回答

1

您在主要功能的错误,你应该在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); 
} 
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; 

另外,出于测试目的,你可能会想要在你的主函数中显示结果。