我正在做一项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;
}我哪里错了?我该在哪里修复这段代码?
发布于 2013-04-26 18:08:25
使用一些数据结构来存储数据。您正在获取多个人的输入,但最终为一个人处理。
而且people--;也完成了。因此BMI变量递减到零,这使得while退出而不执行people计算。
修改代码:
#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-26 18:33:02
现在,您正在处理相同的数据。
每次指定新的值来加权时,旧的值都会被删除。
您可以像这样创建多个变量:
double weight1, weight2, weight3, weight4, ...etc (非常不切实际!!)或者创建一个双精度数组:
double weight[100]; 并像这样引用每个特定的双精度变量:
scanf("%lf %lf", inches[0], weight[0]);
scanf("%lf %lf", inches[1], weight[1]);
scanf("%lf %lf", inches[2], weight[2]);你明白我的意思了吗?您可以通过for循环来操作数组。
https://stackoverflow.com/questions/16233832
复制相似问题