2014-08-29 70 views
0

创建打印出身体质量指数格式指定键入“诠释*”,但参数的类型是“诠释”

printf("What is your height in inches?\n"); 
scanf("%d", height); 

printf("What is your weight in pounds?\n"); 
scanf("%d", weight); 

我有身高和体重作为初始化为int heightint weight代码,但程序不让我运行它,因为它说在scanf行上的格式是int*。我做错了什么让这个程序运行?

+1

备注:良好的代码检查从'scanf()的返回值'。 – chux 2014-08-29 19:49:57

+1

@chux好的代码不使用'scanf()'来读取用户输入。 – 2014-08-30 05:33:20

+1

@顺磁牛角包大多同意和更多。 IMO良好的代码检查'scanf()',更好的代码使用'fgets()'并检查/解析结果。强大的代码使用fgets()来处理文件IO错误。 OP的所有步骤可能都很大,所以推动了第一步。 – chux 2014-08-30 17:12:19

回答

5

scanf要求格式(你的"%d")和变量的内存地址,它应该放置读取的值。 heightweightint,而不是int的存储器地址(这是int *类型'说'的内容:指向存储器地址int的存储器地址)。您应该使用运营商&将内存地址传递给scanf

你的代码应该是:

printf("What is your height in inches?\n"); 
scanf("%d", &height); 

printf("What is your weight in pounds?\n"); 
scanf("%d", &weight); 

更新:作为顺羊角面包指出,引用不正确term.So我改成了内存地址。

+1

什么是“参考”?在C中没有引用。这些是指针。 – 2014-08-30 05:34:08

+0

@顺磁羊角面包C有一个_referenced type_。 “指针类型可以从函数类型或对象类型派生,称为引用类型”C11dr§6.2.520.也许这个答案在该上下文中使用_reference_。 – chux 2014-08-30 17:19:59

+0

@chux我知道这一点,但使用它的问题是不幸的和不正确的,因为引用类型与引用不同,更不用说指针了。 – 2014-08-30 17:20:56

0

scanf从标准输入中读取字符,根据格式说明符"%d"解释整数,并将它们存储在相应的参数中。

要存储它们,您必须指定&variable_name,它将指定输入应存储的地址位置。

scanf的说法应该是:

//For storing value of height 
scanf(" %d", &height); 
//For storing value of weight 
scanf(" %d", &weight); 
1

考虑哪些其他用户都表示,尝试这样的事情;

int height;     <---- declaring your variables 
int weight; 
float bmi;     <---- bmi is a float because it has decimal values 

printf("What is your height in inches?\n"); 
scanf("%d", &height);   <----- don't forget to have '&' before variable you are storing the value in 

printf("What is your weight in pounds?\n"); 
scanf("%d", &weight); 


bmi = (weight/pow(height, 2)) * 703; <---- the math for calculating BMI 
printf("The BMI is %f\n", bmi); 

(为此,你需要将包括文件math.h库)。