用C计算BMI

时间:2015-09-20 14:07:15

标签: c

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
   int userAgeYears = 0;
   int userAgeDays  = 0;
   int userWeight = 0;
   int userHeight = 0;
   int BMI;
   printf("Enter your age in years: \n");
   scanf("%d", &userAgeYears);
   userAgeDays = userAgeYears * 365;
   printf("Enter your weight in pounds: \n");
   scanf("%d", &userWeight);
   printf("Enter your height in inches: \n");
   scanf("%d", &userHeight);
   BMI = ((userWeight/(userHeight * userHeight)) * 703);
   printf("You are %d days old.\n", userAgeDays);
   printf("Your BMI is: %d\n", BMI);
    return 0;
}

//我的BMI结果将计算结果保持为0.

我做错了什么。

3 个答案:

答案 0 :(得分:5)

尝试这样做:

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
   int userAgeYears = 0;
   long userAgeDays  = 0;
   int userWeight = 0;
   int userHeight = 0;
   double BMI;

   printf( "Enter your age in years: \n" );
   scanf( "%d", &userAgeYears );
   userAgeDays = userAgeYears * 365;
   printf( "Enter your weight in pounds: \n" );
   scanf( "%d", &userWeight );
   printf( "Enter your height in inches: \n" );
   scanf( "%d", &userHeight );

   BMI = ( userWeight / (double)(userHeight * userHeight) ) * 703;

   printf( "You are %ld days old.\n", userAgeDays );
   printf( "Your BMI is: %02f\n", BMI );

   return 0;
}

发生这种情况是因为您将所有变量定义为整数,并将userWeight/(UserHeight*UserHeight)的答案四舍五入为0

答案 1 :(得分:2)

这是C / C ++中非常常见的错误。除非将其强制转换为其他类型,否则除以两个整数的结果是整数,因此除法值将在每一步都被截断。

由于在乘以703转换因子之前将权重除以高度平方,因此将其截断为零。 (有重量和高度值,它不会为零,但由于精度损失,计算仍然不准确。)

最好的办法是强制转换为双倍或读取原始值为双精度数。只要一个操作符是float或double,就不会发生截断。

答案 2 :(得分:0)

这一行:

BMI = ((userWeight/(userHeight * userHeight)) * 703);

正在使用整数数学。在整数数学中,如果除数大于被除数,则结果始终为0.建议:

BMI = (( (float)(userWeight) /(userHeight * userHeight)) * 703);

然后将所有值转换为'float'计算结果,并将'floor()'值转换为'BMI'