0
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", &centimeter);
//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 语句的程序?请帮帮我,非常感谢

4

3 回答 3

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。您可以将 else if 更改为 if。

if (userInput == 'C')
    userInput = 'c';
if (userInput == 'c'){
    printf("\nEnter the length in centimeter:  ");
    ...
}
于 2013-09-29T12:44:51.213 回答
2

改变:

meterFloat = (centimeter * 1/100);

至:

meterFloat = (centimeter * 1.0/100);

centimeter,1并且100都是ints, 导致整数的乘法和除法。使用整数除法,centimeter/100很可能是0,除非centimeter> 100

于 2013-09-29T12:52:01.063 回答
1

改变

int centimeter;
int meter;

float centimeter;
float meter; 

并 输入%d为 十进制,因为您将输入存储在和%fscanfmetercentimeter

于 2013-09-29T12:41:08.433 回答