首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BMI分类结构

BMI分类结构
EN

Stack Overflow用户
提问于 2013-04-26 18:05:31
回答 2查看 835关注 0票数 1

我正在做一项C语言的作业,我必须读取多个人的身高和体重,并确定他们的bmi。然后我将它们归入各自的bmi类别,但我被困在如何正确地做到这一点上,这是我到目前为止的代码:

代码语言:javascript
复制
# 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;
}

我哪里错了?我该在哪里修复这段代码?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-04-26 18:08:25

使用一些数据结构来存储数据。您正在获取多个人的输入,但最终为一个人处理。

而且people--;也完成了。因此BMI变量递减到零,这使得while退出而不执行people计算。

修改代码:

代码语言:javascript
复制
#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;
}
票数 1
EN

Stack Overflow用户

发布于 2013-04-26 18:33:02

现在,您正在处理相同的数据。

每次指定新的值来加权时,旧的值都会被删除。

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

double weight1, weight2, weight3, weight4, ...etc (非常不切实际!!)或者创建一个双精度数组:

代码语言:javascript
复制
double weight[100]; 

并像这样引用每个特定的双精度变量:

代码语言:javascript
复制
scanf("%lf %lf", inches[0], weight[0]);
scanf("%lf %lf", inches[1], weight[1]);
scanf("%lf %lf", inches[2], weight[2]);

你明白我的意思了吗?您可以通过for循环来操作数组。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16233832

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档