2017-08-13 14 views
1

我现在正在练习c编程,并且制作了一些BMI计算器。它工作的很好,但是当用户输入字符串或字符的第一个scanf发送数据浮动变量'重量'。之后它通过了所有scanf,并向我显示出Your BMI is 1.#J的错误。如何解决这个错误?这是我的代码。当用户在scanf中输入字符串并保持浮点型变量时获取错误

#include <stdio.h> 

int main() 
{ 
    float weight; 
    float height; 
    float result; 
    float c_height; 

    printf("Enter your weight as kilogram...\n\n> "); 
    scanf("%f",&weight); 
    //If user input char or string , it passed all thing and showed error. 

    printf("\nEnter your height as centimetres...\n\n> "); 
    scanf("%f",&height); 

    c_height=(height/100)*(height/100); 
    result=weight/c_height; 

    if(result<18.50) 
    { 
    printf("\nYour BMI is %.2f\n\n",result); 
    printf("You are underweight! Try to eat more frequently\n\n"); 
    printf("Thank you for using my program!\n\n"); 

}else if(result>=18.50 && result<22.90) 
{ 
    printf("\nYour BMI is %.2f\n\n",result); 
    printf("You are healthy! Keep eating healthy\n\n"); 
    printf("Thank you for using my program!\n\n"); 

}else if(result>=22.90 && result<24.90) 
{ 
    printf("\nYour BMI is %.2f\n\n",result); 
    printf("You are a little overweight! Avoid eating some fat and an oil\n\n"); 
    printf("Thank you for using my program!\n\n"); 

}else if(result>=24.90 && result<29.90) 
{ 
    printf("\nYour BMI is %.2f\n\n",result); 
    printf("You are overweight! Avoid eating fat and do exercise often\n\n"); 
    printf("Thank you for using my program!\n\n"); 

}else if(result>=29.90) 
{ 
    printf("\nYour BMI is %.2f\n\n",result); 
    printf("You are obese! Do exercise everyday and eat carefully!\n\n"); 
    printf("Thank you for using my program!\n\n"); 

}else 
{ 
    printf("Error occured!!"); 
} 
return 0; 

}

+0

为什么进入焦炭scanf函数后或字符串,当有人要求重量,并在浮动[格式说明符](https://www.le.ac.uk/users/rjm1/cotter/page_30.htm) – wrangler

回答

4

scanf函数将返回值的数量读取,所以应该是一个在你的榜样,因为你是在一个浮点值读取。

你可以检查scanf函数返回值,如果它没有做一些恢复的,如阅读,直到行尾:

while(scanf("%f",&height) != 1) 
{ 
    int c; 
    while((c = getchar()) != '\n' && c != EOF) 
    ; 
    printf("Enter your weight as kilogram...\n\n> "); 
} 
+1

这是正确的做法,虽然它会如果while循环在达到EOF而不是换行符时发生保留错误条件,则更好。无论如何,值得提升。 – WhozCraig

0

传递到下一个参数添加一个fflush(标准输入)

scanf("%f",&weight); 

    fflush(stdin); 

,你需要你的CONTROLE输入这样的:

if (scanf("%lf", &weight) == 1) 
    printf("It's float: %f\n", weight); 
else 
    printf("It's NOT float ... \n"); 
+1

*“添加fflush(stdin)...”* - 或*不*。这种行为不是由语言标准或其库来定义的。只应在* output *流或最后一个操作是* output *的输入/输出流上调用'fflush'。 – WhozCraig

+0

是真的,但有了它,他可以传递给下一个“scanf”,这就是他想要的。 –

+1

请参阅[使用'fflush(stdin)'](http://stackoverflow.com/questions/2979209/using-fflushstdin)获取细微差别,但要谨慎使用它 - 并且不要在Windows平台上使用它。 –

相关问题