Reputation: 63
#include <stdio.h>
int main(){
double km, miles, yards, feet, inches;
scanf("%lf", &km);
miles = km/1.609;
printf("%d\n", (int)miles);
yards = ((km*1093.61) - ((int)miles*1760));
printf("%d\n", (int)yards);
feet = (km*3281.4) - ((int)miles*5280 + yards*3);
printf("%d\n", (int)feet);
inches = km*39378.498 - ((int)miles*63360 + (int)yards*36 + (int)feet*12);
printf("%.2lf", inches);
return 0;
}
This is what I managed to write, however it still doesn't pass all tests and isn't 100% accurate as seen in the image below
Help would be highly appreciated.
Upvotes: 1
Views: 635
Reputation: 51825
When writing code to do conversions such as in your task, it is better to do all (internal) calculations in double
precision and convert each component part of the result (to int
) 'on the fly', then subtract each of those converted values as they are determined.
So, first get the conversion into miles as a double
value, then subtract each integral part and multiply the remainder by the factor required to get the next sub-unit. Using this approach, you are far less likely to encounter problems due to integer overflow and rounding errors.
The following is a potential solution. (Note that it is far better to write clear code than attempt to 'compress' many operations into single-line code; the latter is a common cause for bugs creeping into your code and also makes it more difficult for future developers of your code to understand and/or modify it.)
#include <stdio.h>
int main()
{
double km = -1.0, total, inches;
int miles, yards, feet;
do {
printf("Enter value in Km: ");
if (scanf("%lf", &km) != 1) { // Error input: clear buffer
int c;
while ((c = getchar()) != '\n' && c != EOF)
;
if (c == EOF) return 1; // Can't do much after an EOF!
}
} while (km < 0.0);
// First, do the conversion to double "total" ...
total = km / 1.609;
// Now, get the integer "miles" value and subtract that from the total ...
miles = (int)total;
total -= (double)miles;
// Next, multiply remainder by 1760 to get the number of yards ...
total *= 1760.0;
// Now, get the integer value and subtract that from total ...
yards = (int)total;
total -= (double)yards;
// Multiply remainder by 3 to get feet ...
total *= 3.0;
feet = (int)total;
total -= (double)feet;
// Finally, multiply remainder by 12 to get inches ...
inches = total * 12.0;
// Display result:
printf("%d %d %d %.2lf\n", miles, yards, feet, inches);
return 0;
}
Note that I have also added some code to check that the input value is 'acceptable' (I have chosen to reject negative values, but you can easily change that condition); more importantly, the code will also be able to deal with situations where the user enters a value that cannot be interpreted as a floating-point input (like "Fred"). When using scanf
for user input, it is always a good idea to check for valid input and handle possible error conditions.
Upvotes: 1