I have the following function prototype:
int ForeignTimeToEastern (int hour, int adjustment);
I need to write C code that converts London time, Stockholm, etc to eastern time using that prototype. Here's more info:
* London time is 5 hours ahead of Eastern Time
* Stockholm time is 6 hours ahead of Eastern Time
*Tampere and Helsinki time is 7 hours ahead of Eastern Time
* St. Petersburg time is 8 hours ahead of Eastern Time
Please help!! thanks
How to write this C code?
I'd use something like shown below
int ForeignTimeToEastern (int hour, int adjustment)
{
int temptime;
int timefactor;
switch (adjustment)
{
case 0: timefactor=-5; // london time
break;
case 1: timefactor=-6; // stockhom time
break;
case 2: timefactor=-7; // tampere and helsinki
break;
case 3: timefactor=-8; // st. pete
}
temptime=time+timefactor;
//need to check for time out of range
if (temptime %26lt;= 0) temptime = temptime + 12; //or 24 if you are using 24 hour time
return (temptime);
}
Reply:If you use BillM's code you will get the wrong answer in every case except case 3 (St. Petersburg). The reason is that he did not include "break" statements at the end of his cases, so the execution will just continue into the next case, whether the "adjustment" matches that case or not. So, regardless of the "adjustment" value, the final value of the "timefactor" variable will always be "-8".
To fix, change as follows:
case 0: timefactor=-5; // london time
break;
case 1: timefactor=-6; // stockhom time
break;
case 2: timefactor=-7; // tampere and helsinki
break;
case 3: timefactor=-8; // st. pete
break;
Furthermore it is really error-prone to NOT have a "default" case to handle erroneous values of "adjustment".
-------------
EDIT: it looks like he changed his code to include the "break" statements I suggested. Still no "default" case though. Maybe he'll catch that in the next edit.
Reply:I'm not sure what "adjustment" is supposed to represent, but it looks to me like it is the offset from the foreign time to eastern time. So the function is easy:
int ForeignTimeToEastern(int hour, int adjustment)
{
return (hour + adjustment) % 24;
}
So for London call ForeignTimeToEastern(hour, -5). Etc.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment