2013-04-26 36 views
1

我正在C中进行一项任务,在C中我必须阅读多个人的身高和体重并确定他们的bmi。然后,我把它们归类到各自的BMI类别,但我被陷在如何做到这一点正确的,这是我的代码至今:BMI分类结构

# include <stdio.h> 

int main() { 

    int people; 
    double bmi, weight, inches; 

      printf("How many peoples? > "); 
      scanf("%d", &people); 

    do { 
      printf("Enter height (inches) and weight (lbs) (%d left) > ", people); 
      scanf("%lf %lf", &inches, &weight); 
      people--; 
    } 

    while (people > 0); 

      bmi = (weight/(inches * inches)) * 703; 

      if (bmi < 18.5) { 
        printf("Under weight: %d\n", people); 
      } 
      else if (bmi >= 18.5 && bmi < 25) { 
        printf("Normal weight: %d\n", people); 
      } 
      else if (bmi >= 25 && bmi < 30) { 
        printf("Over weight: %d\n", people); 
      } 
      else if (bmi >= 30) { 
        printf("Obese: %d\n", people); 
      } 
return 0; 
} 

我在哪里去了?我在哪里修复此代码?

回答

1

使用一些数据结构来存储数据。您获得了多于一个人的输入,但最终只能处理一个人。

而且people--;完成。所以people变量减少到零,这使得while退出而不执行您的BMI计算。

修改代码:

#include <stdio.h> 

#define MAX_PEOPLE  100 

int main() { 

    int people; 
    double bmi[MAX_PEOPLE], weight[MAX_PEOPLE], inches[MAX_PEOPLE]; 

    int index = 0; 

      printf("How many peoples? > "); 
      scanf("%d", &people); 

    index = people; 

    do { 
      printf("Enter height (inches) and weight (lbs) (%d left) > ", index); 
      scanf("%lf %lf", &inches[index], &weight[index]); 
      index--; 
    }while (index > 0); 

     for(index = 0; index < people; index++) 
     { 

      bmi[index] = (weight[index]/(inches[index] * inches[index])) * 703; 

      if (bmi[index] < 18.5) { 
        printf("Under weight: %d\n", index); 
      } 
      else if (bmi[index] >= 18.5 && bmi[index] < 25) { 
        printf("Normal weight: %d\n", index); 
      } 
      else if (bmi[index] >= 25 && bmi[index] < 30) { 
        printf("Over weight: %d\n", index); 
      } 
      else if (bmi[index] >= 30) { 
        printf("Obese: %d\n", index); 
      } 
     } 
return 0; 
} 
+0

你是否建议分配另一个变量来表示“people--”,比如y = people--;? – Student 2013-04-26 10:18:47

+0

请参阅我更新的代码,并尝试按照您的风格进行操作。 – Jeyaram 2013-04-26 10:23:35

+0

谢谢!即时通讯将使用你所做的,并重新编写我的代码,所以我可以肯定,我完全理解它 – Student 2013-04-26 10:32:39

0

现在你正在处理相同的数据。

每次您为重量指定一个新值时,旧的值将被删除。

您可以创建多个变量,像这样:

double weight1, weight2, weight3, weight4, ...等(高度不实用!!) 或 创建双打的数组:

double weight[100]; 

,并参考各个特定的双变量像这样:

scanf("%lf %lf", inches[0], weight[0]); 
scanf("%lf %lf", inches[1], weight[1]); 
scanf("%lf %lf", inches[2], weight[2]); 

你看到我在哪里?您可以操作阵列tru a for loop

+0

所以我能够重新编写代码,但输出我需要遵循以下详细说明的某种方式,在使用它一段时间后我无法得到它,我的输出应该如下所示:处理3人,并发现:重量不足:0正常体重:1超重:1肥胖:1警告!人口可能是不健康的,它实际上打印出所有0的类别,然后我加总超重和肥胖的总值,如果这个值超过总数的一半,那么我打印警告,但是我似乎只得到在该BMI范围内的 – Student 2013-04-26 16:01:52

+0

人的打印声明,即没有“0正常体重的人”等,我似乎不知道如何总是存储数据,所以我总是有打印每个类别,即使其为零,然后如何引用回该数据以便能够再次比较以查看整体流行音乐是否超重,将不胜感激任何帮助 – Student 2013-04-26 16:02:39