c - 当用户在保持 float 变量的 scanf 中输入字符串时出错

标签 c codeblocks

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

#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;

最佳答案

scanf 将返回读入的值的数量,因此在您的示例中应该是一个,因为您正在读取单个浮点值。

您可以检查 scanf 是否返回该值,以及它是否不进行某种恢复,例如读取到行尾:

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

关于c - 当用户在保持 float 变量的 scanf 中输入字符串时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45656148/

相关文章:

c - 使用 malloc 的段错误,用于合并排序的结构数组

c - C 编译器接受的可疑 case 语句语法

c - 按值将数组传递给函数

c - 字符串数组的 malloc 时出现段错误。如何摆脱它?当分配第二个维度时,我可以发现它精确地发生

c++ - 简单的 "Hello World"代码没有出现在命令提示符中

c - 左操作数必须是左值

lua - 代码块的脚本语言

php - PCRE:为代码块找到匹配的大括号

c++ - 当一个功能完成另一个功能打开时我该怎么办?

编译困境(代码块和ubuntu)