patterncMajor
Converting inches to feet
Viewed 0 times
convertingfeetinches
Problem
This was a homework assignment that I'm now done with - I submitted it as is. However the fact that I needed to use the same code twice bugged me... The double code is:
Is there a better way to do the same thing in my loop instead of the double
printf("Enter a distance in inches (0 to quit): ");
scanf("%f",&input);Is there a better way to do the same thing in my loop instead of the double
scanf/printf? It does need to quit the program immediately if a 0 is entered.#include
int main()
{
float distance, floatFeet, input;
int feet;
printf("Enter a distance in inches (0 to quit): ");
scanf("%f", &input);
while (input != 0)
{
feet = input/12;
distance = (input-feet*12);
floatFeet = input/12;
printf("%d feet and %f inches or %f feet \n\n", feet, distance, floatFeet);
printf("Enter a distance in inches (0 to quit): ");
scanf("%f", &input);
}
}Solution
You could move the duplicated lines into a function, something like this should work:
#include
float get_input(void)
{
float input;
printf("Enter a distance in inches (0 to quit): ");
scanf("%f", &input);
return input;
}
int main()
{
float inches, floatFeet, input;
int feet;
while (input = get_input())
{
feet = input/12;
inches = (input-feet*12);
floatFeet = input/12;
printf("%d feet and %f inches or %f feet \n\n",feet,inches,floatFeet);
}
printf("Goodbye!\n");
}Code Snippets
#include <stdio.h>
float get_input(void)
{
float input;
printf("Enter a distance in inches (0 to quit): ");
scanf("%f", &input);
return input;
}
int main()
{
float inches, floatFeet, input;
int feet;
while (input = get_input())
{
feet = input/12;
inches = (input-feet*12);
floatFeet = input/12;
printf("%d feet and %f inches or %f feet \n\n",feet,inches,floatFeet);
}
printf("Goodbye!\n");
}Context
StackExchange Code Review Q#23021, answer score: 30
Revisions (0)
No revisions yet.