Format指定类型“int *”但参数的类型为“int”

时间:2014-08-29 19:27:49

标签: c

创建打印出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 heightint weight,但程序不允许我运行它,因为它表示int*上的格式为scanf行。为了让这个程序运行,我做错了什么?

4 个答案:

答案 0 :(得分:9)

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);

更新:正如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)值时,您必须将内存地址传递给该原语值。但是,仅添加尚未提及的内容,对于字符串来说并非如此。

示例1.与原始值一起使用

#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.)
}

示例2。不使用原始值

#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
}