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;
}
这是我的代码但是当我把输入作为小数时,输出没有正确输出请帮助,如果我放10cm米的结果不是小数而是0和另外一个问题,如何制作if else语句的异常处理程序?请帮帮我,非常感谢你
答案 0 :(得分:2)
我看到的一个问题是你的if,else if结构。
//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: ");
...
}
如果用户输入'C',程序会设置userInput,但是如果用户输入则不会进入。您可以将else更改为if。
if (userInput == 'C')
userInput = 'c';
if (userInput == 'c'){
printf("\nEnter the length in centimeter: ");
...
}
答案 1 :(得分:2)
变化:
meterFloat = (centimeter * 1/100);
为:
meterFloat = (centimeter * 1.0/100);
centimeter
,1
和100
都是int
s,导致整数乘法和除法。
使用整数除法,centimeter/100
可能为0
,除非centimeter
> 100
。
答案 2 :(得分:1)
更改
int centimeter;
int meter;
到
float centimeter;
float meter;
%d
中的和%f
到scanf
输入为十进制,因为您将输入存储在meter
和centimeter