我正在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;
}
我哪里错了?我在哪里修复此代码?
答案 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;
}
答案 1 :(得分: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 loop 。