1

我正在用 C 做一个作业,我必须阅读多个人的身高和体重并确定他们的 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;
}

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

4

2 回答 2

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;
}
于 2013-04-26T10:08:25.077 回答
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 一个for 循环

于 2013-04-26T10:33:01.950 回答