创建打印出Body Mass Index的代码
printf("What is your height in inches?\n");
scanf("%d", height);
printf("What is your weight in pounds?\n");
scanf("%d", weight);
我的身高和体重已初始化为int height
,int weight
,但程序不允许我运行它,因为它表示int*
上的格式为scanf
行。为了让这个程序运行,我做错了什么?
答案 0 :(得分:9)
scanf
需要格式(您的"%d"
)以及变量的内存地址,它应该放置已读取的值。 height
和weight
是int
,而不是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);
更新:正如The Paramagnetic Croissant所指出的那样,参考不是正确的术语。所以我把它改成了记忆地址。
答案 1 :(得分: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库。)
答案 2 :(得分:0)
scanf
从标准输入中读取字符,根据这里的格式说明符"%d"
解释整数,并将它们存储在相应的参数中。
要存储它们,您必须指定&variable_name
,它将指定应存储输入的地址位置。
您的scanf
声明应为:
//For storing value of height
scanf(" %d", &height);
//For storing value of weight
scanf(" %d", &weight);
答案 3 :(得分:0)
就像其他人所说的,这是因为当您有一个用scanf读取的原语(例如int)值时,您必须将内存地址传递给该原语值。但是,仅添加尚未提及的内容,对于字符串来说并非如此。
#include <stdio.h>
int main()
{
int primitiveInteger; // integer (i.e. no decimals allowed)
scanf("%i", &primitiveInteger); // notice the address of operator getting the address of the primitiveInteger variable by prepending the variable name with the & (address of) operator.
printf("Your integer is %i", primitiveInteger); simply printing it out here to the stdout stream (most likely your terminal.)
}
#include <stdio.h>
int main()
{
char *nonPrimitiveString; // initialize a string variable which is NOT a primitive in C
scanf("%s", nonPrimitiveString); // notice there is no address of operator here
printf("%s\n", nonPrimitiveString); // prints string
}