Skip to content

Instantly share code, notes, and snippets.

@dhhdev
Created January 22, 2018 21:53
Show Gist options
  • Save dhhdev/d846f6433e70134444ce0a0e04d848ed to your computer and use it in GitHub Desktop.
Save dhhdev/d846f6433e70134444ce0a0e04d848ed to your computer and use it in GitHub Desktop.
Distance, speed, and time calculator. Measure time taken with certain distance and speed, or get the speed needed to travel a certain distance within a certain time.
#include <stdio.h>
#include <stdlib.h>
#define PROGRAM_NAME "dst"
#define AUTHOR "Daniel H. Hemmingsen"
typedef enum {FALSE, TRUE} BOOLEAN;
/*
* distance = speed * time
* speed = distance / time
* time = distance / speed
*/
BOOLEAN calculate(double *distance, double *speed, double *time)
{
if (*distance <= 0 && *speed > 0 && *time > 0) {
printf("Calculating distance...\n");
*distance = *speed * *time;
} else if (*distance > 0 && *speed <= 0 && *time > 0) {
printf("Calculating speed...\n");
*speed = *distance / *time;
} else if (*distance > 0 && *time <= 0 && *speed > 0) {
printf("Calculating time...\n");
*time = *distance / *speed;
} else {
return FALSE;
}
return TRUE;
}
BOOLEAN human_time(double *time, int *hours, int *minutes, int *seconds)
{
*seconds = *time * 60 * 60;
if (*seconds >= 60) {
while (*seconds >= 60) {
*seconds = *seconds - 60;
*minutes = *minutes + 1;
}
}
if (*minutes >= 60) {
while (*minutes >= 60) {
*minutes = *minutes - 60;
*hours = *hours + 1;
}
}
return TRUE;
}
void usage(char *executable)
{
printf("Usage: %s distance speed time\n\n", executable);
printf("You need to at least know two of the three values.\n");
printf("Simply use 0 if you don't know the value.\n\n");
printf("Example: %s 10 30 0\n", executable);
}
int main(int argc, char *argv[])
{
double distance, speed, time;
int hours, minutes, seconds;
BOOLEAN success;
if (argc != 4) {
usage(argv[0]);
return EXIT_FAILURE;
}
distance = atof(argv[1]);
speed = atof(argv[2]);
time = atof(argv[3]);
success = calculate(&distance, &speed, &time);
if (success) {
printf("Calculation is done...\n\n");
printf("Distance:\t%.2f km.\n", distance);
printf("Speed:\t\t%.2f km/h.\n", speed);
} else {
usage(argv[0]);
return EXIT_FAILURE;
}
success = human_time(&time, &hours, &minutes, &seconds);
if (success) {
printf("\nHuman Readable Time (H:M:S)\n\n");
printf("%d:%d:%d\n", hours, minutes, seconds);
} else {
printf("\n\nCouldn't Calculate Human Readable Time (H:M:S)\n\n");
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment