我这边有问题
typedef struct
{
int hours;
int minutes;
int seconds;
} Time;
Time calcTime(Time time1, Time time2)
{
Time calc1;
Time calc2;
calc1.hours - calc2.hours;
return calc1; // How do I print this outside the function?
}
如何打印 calc1.seconds OUTSIDE函数?
答案 0 :(得分:5)
这就是你可以做到的。
Time t = calcTime(time1, time2);
printf("%d %d %d\n", t.hours, t.minutes, t.seconds);
但是,请使用time_t
中的struct tm
,time.h
进行相关实施。
您可以找到更多信息here或示例here。
calcTime
Time calcTime(Time calc1, Time calc1)
{
// Do not re declare the function arguments.
//Time calc1;
//Time calc2;
// This has no effect, unless you store the result
// calc1.hours - calc2.hours;
calc1.hours -= calc2.hours; // short for calc1.hours = calc1.hours - calc2.hours
// you need to also check if hours has a valid value after the operation
if(calc1.hours < 0 || calc1.hours > 24) {
// error
}
return calc1;
}
答案 1 :(得分:2)
即使您调用该函数,它也无法正常工作,因为您正在减去未初始化的变量。您在time1
中不需要time2
和calcTime
,而只需像这样定义您的函数:
Time calcTime(Time calc1, Time calc2)
{
//Time calc1;
//Time calc2;
// calc1.hours - calc2.hours; --> You are not storing the value here
calc1.hours -= calc2.hours; // or you should write --> calc1.hours = calc1.hours - calc2.hours
return calc1;
}
并致电main
:
int main()
{
Time t1,t2;
t1.hours = 10;
t2.hours = 5;
t2 = calcTime(t1, t2);
printf("The time is %d hours", t2.hours);
}
答案 2 :(得分:1)
只需调用该函数(另请注意,我已将您的函数更改为实际返回相关值)。
typedef struct
{
int hours;
int minutes;
int seconds;
} Time;
Time calcTime(Time calc1, Time calc2)
{
calc1.hours = calc1.hours - calc2.hours;
return calc1;
}
int main()
{
Time t1;
Time t2;
t1.hours = 10;
t2.hours = 5;
Time t3 = calcTime(t1, t2);
printf("The time is %d hours", t3.hours);
}