write a function that accepts three arguments a number n, and two character s and t. the function covert n from s unit to t unit of similar physical quantities. you can choose one of the following types to use in your program. 1.length 2.temperature 3.area 4.volume 5.weight 6.time
#include <stdio.h>
/***************************************************
* Convert time
* 'n' - nanoseconds
* 'u' - microseconds
* 'l' - miliseconds
* 's' - seconds
* 'm' - minutes
* 'h' - hours
* 'd' - days
* 'W' - weeks
* 'M' - months
* 'Y' - years
* 'C' - ceturies
**************************************************/
double time_convert(double x, char source, char target)
{
double t; /* time in seconds */
double res;
switch (source) {
case 'C':
t = x * 100 * 365.25 *24 * 3600;
break;
case 'Y':
t = x * 365.25 * 24 * 3600;
break;
case 'M':
t = x * 30 * 24 * 3600;
break;
case 'W':
t = x * 7 * 24 * 3600;
break;
case 'd':
t = x * 24 * 3600;
break;
case 'h':
t = x * 3600;
break;
case 'm':
t = x * 60;
break;
case 's':
t = x;
break;
case 'l':
t = x / 1000;
break;
case 'u':
t = x / 1e6;
break;
case 'n':
t = x / 1e9;
break;
default:
fprintf(stderr, "Unknown source units: %c\n", source);
return 0;
}
\
switch (target) {
case 'C':
res = t / (100 * 365.25 *24 * 3600);
break;
case 'Y':
res = t / (365.25 * 24 * 3600);
break;
case 'M':
res = t / (30 * 24 * 3600);
break;
case 'W':
res = t / (7 * 24 * 3600);
break;
case 'd':
res = t / (24 * 3600);
break;
case 'h':
res = t / 3600;
break;
case 'm':
res = t / 60;
break;
case 's':
res = t;
break;
case 'l':
res = t * 1000;
break;
case 'u':
res = t * 1e6;
break;
case 'n':
res = t * 1e9;
break;
default:
fprintf(stderr, "Unknown target units: %c\n", target);
return 0;
}
return res;
}
int main() {
double t1=1, t2;
t2 = time_convert(t1, 'C', 's');
printf("There are %e seconds in %.1f century\n", t2, t1);
return 0;
}
Comments
Leave a comment