Convert KM/HR to M/S
Convert a speed value from kilometers per hour to meters per second with specific precision requirements
Understand the Problem
Problem Statement
Speed S of a car is passed as input. It is in kilometers per hour. Write a program to convert the speed from kilometer per hour to meter per second.
Constraints
- 0 < S < 4500 (Speed in km/h)
- Input must be a positive integer
- Output must be limited to exactly two decimal places without rounding up
- Speed conversion formula: m/s = km/h × 1000 ÷ 3600
Examples
23063.88Speed of the car in meter per second = 230 × 1000 ÷ 3600 = 63.888... which is truncated to 63.88 (two decimal places without rounding)
Solution
#include <stdio.h>
int main() {
int speed_kmh;
scanf("%d", &speed_kmh);
double speed_ms = speed_kmh * 5.0 / 18.0;
// Convert to string with sufficient precision
char buffer[50];
sprintf(buffer, "%.10f", speed_ms);
// Find decimal point
char *decimal_point = strchr(buffer, '.');
if (decimal_point != NULL) {
// Print up to decimal point
for (char *p = buffer; p < decimal_point; p++) {
printf("%c", *p);
}
printf(".");
// Print exactly 2 decimal places
printf("%c", *(decimal_point + 1));
printf("%c", *(decimal_point + 2));
} else {
// No decimal point, print as is and add .00
printf("%s.00", buffer);
}
printf("\n");
return 0;
}The C solution reads an integer speed in km/h, converts it to m/s by multiplying by 5.0/18.0, then uses sprintf with high precision to convert to string. It finds the decimal point using strchr, prints everything before the decimal point, then prints exactly the next two characters after the decimal point. If there's no decimal point, it appends ".00" to maintain the two-decimal format.