Reputation: 11
int main(int argc, const char * argv[])
{
char userInput;
int centimeter;
int meter;
float centimeterFloat = 0.0;
float meterFloat = 0.0;
printf("Enter c for centimeter to meter OR m for meter to centimeter: ");
userInput = getchar();
//If the user types in 'm' or 'M' the progrsm will ask you to type in the length in meters and it will converts to centimeters.
if (userInput == 'M')
userInput = 'm';
if (userInput == 'm')
{
//This calculation is to convert meters to centimeters.
printf("\nEnter the length in meter: ");
scanf("%d", &meter);
centimeterFloat
= (meter * 100);
printf("\nmeter\tcentimeter\n");
printf("%d\t\t\t%4.0f\n", meter, centimeterFloat);
}
//If the user types in 'c' or 'C' the program will ask you to type in the length in centimeters and it will converts to meters.
if (userInput == 'C')
userInput = 'c';
else if (userInput == 'c')
{
printf("\nEnter the length in centimeter: ");
scanf("%d", ¢imeter);
//This calculation is to convert centimeters to meters.
meterFloat = (centimeter * 1/100);
printf("\nmeter\tcentimeter\n");
printf("%3.1f\t\t\t%d\n", meterFloat, centimeter);
}
return 0;
}
This is my code but when I put my input as decimals, the output does not come out properly please help and if I put 10cm the results of meters does not come out as decimal but 0 and one more question, how to make an exception handling program with if else statement? please help me thank you so much
Upvotes: 0
Views: 5702
Reputation: 100638
Change:
meterFloat = (centimeter * 1/100);
to:
meterFloat = (centimeter * 1.0/100);
centimeter
, 1
and 100
are all int
s, resulting in integer multiplication and division.
Using integer division, centimeter/100
is likely to be 0
, unless centimeter
> 100
.
Upvotes: 2
Reputation: 2562
One problem that I see is with your if, else if structure.
//If the user types in 'c' or 'C' the program will ask you to type in the length in centimeters and it will converts to meters.
if (userInput == 'C')
userInput = 'c';
else if (userInput == 'c'){
printf("\nEnter the length in centimeter: ");
...
}
If the user enters 'C' the program sets the userInput, but then it won't get inside of the else if. You could change the else if to an if.
if (userInput == 'C')
userInput = 'c';
if (userInput == 'c'){
printf("\nEnter the length in centimeter: ");
...
}
Upvotes: 2
Reputation: 105992
Change
int centimeter;
int meter;
to
float centimeter;
float meter;
and %d
to %f
in scanf
to input as decimal, because you are storing your input in meter
and centimeter
Upvotes: 1