我希望函数getCategory()返回" invalid“,而不是在函数的输入无效(i.e.when身高或体重都小于0)时打印"invalid”(即,而不是使用printf )。请帮助:
#include<stdio.h>
#include<conio.h>
char getCategory(float height,float weight)
{
char invalid = '\0';
float bmirange;
if(height<=0 || weight<=0)
return invalid;
else
{
height=height*0.01;
bmirange=[weight/(height*height)];
if(bmirange< 15 )
return starvation;
}
}
/* return the following to category
If bmi range < 15 then category is "starvation"
If bmi range >=15 && bmi range < 18.5 then category is "underweight"
If bmi range >=18.5 && bmi range < 25 then category is "normal"
If bmi range >= 25 && bmi range < 30 then category is "overweight"
If bmi range >=30 && bmi range < 40 then category is "obese"
If bmi range >=40 then category is "morbidly obese
*/
int main()
{
char Category;
float height,weight;
printf("enter height");
scanf("%f",&height);
printf("enter weight");
scanf("%f",&weight);
Category=getCategory(height,weight);
if(Category == 0)
printf("invalid");
else
printf("%c", Category);
}发布于 2009-12-05 01:23:43
将返回类型更改为char *,然后返回指向各种类别字符串的指针。您还需要填写各种bmi级别的检查。
看起来很像家庭作业;如果是这样,请标记出来。
这是我的解决方案。但我已经对行的顺序进行了随机化,因为您确实需要自己做功课。不过,这里面应该有一些提示,比如struct和return行。
scanf("%f",&height);
struct bmicategory {
}
{18.5, "normal"},
return categories[i-1].name;
float bmi = weight / (height * height);
struct bmicategory categories[] = {
printf("enter weight (in kg): ");
};
char *name;
return 0;
{40, "morbidly obese"},
{15, "underweight"},
}
scanf("%f",&weight);
for(i=1; i<sizeof(categories)/sizeof(struct bmicategory); i++) {
#include<stdio.h>
if(bmi < categories[i].value) {
break;
printf("%s\n", category);
height = height * 0.01;
printf("enter height (in cm): ");
{25, "overweight"},
category=getBmiCategory(height,weight);
int main() {
float value;
int i;
/* printf("BMI = %f\n", bmi); */
}
};
float height;
{30, "obese"},
}
char *category;
char *name = NULL;
{0, "starvation"},
char *getBmiCategory(float height, float weight) {
float weight;发布于 2009-12-05 01:29:56
我不明白你有什么问题。不能根据参数更改返回类型。要么始终返回类型char,要么始终返回字符串。这是一个语言限制(我想说的是一个很好的限制)。
我可以想出两种方法来解决这个问题。第一种方法是返回一个对象或指向内存的指针。但是,在获得结果之后,您仍然需要根据返回类型来派生代码。
在您的案例中,您实际上描述了异常的典型用例。如果其中一个参数小于零,则抛出异常。然后,您可以使用try-catch构造在main中捕获异常,并从那里继续。
https://stackoverflow.com/questions/1848394
复制相似问题