C使用Xcode 运行这个小脚本时,我收到以下消息:
Format specifies type 'float *' but the argument has type 'double" at scanf("%f", v) and scanf("%f", i).
我没有得到它,因为我没有声明任何double类型变量.
int main(int argc, const char * argv[]) {
char choice[10];
float v;
float i;
float r;
printf("What would you like to calculate?: ");
scanf("%s", choice);
printf("\nYou chose: \n""%s", choice);
if (strcmp(choice, "r") == 0)
{
printf("\nPlease enter voltage (V): \n");
scanf("%f", v);
printf("\nPlease enter current (I): \n");
scanf("%f", i);
r = v/i;
printf("%f", r);
}
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
您收到该警告是因为您未能将指向float(float*)的指针传递给该函数scanf.编译器告诉你它是double,因为它scanf是一个可变参数函数.变量参数受默认参数提升的约束,其中某些数据类型的参数被转换为更大的数据类型.在这种情况下,float被提升为double.
在C函数的唯一方法修改变量v,i以及choice是通过他们为指针,所以你需要传递指针scanf,使用&运营商"的地址".
您的代码应如下所示:
int main(int argc, const char * argv[]) {
char choice[10];
float v;
float i;
float r;
printf("What would you like to calculate?: ");
scanf("%9s", &choice); /* this specifier prevents overruns */
printf("\nYou chose: \n""%s", choice);
if (strcmp(choice, "r") == 0)
{
printf("\nPlease enter voltage (V): \n");
scanf("%f", &v); /* use a pointer to the original memory */
printf("\nPlease enter current (I): \n");
scanf("%f", &i); /* use a pointer to the original memory */
r = v/i;
printf("%f", r);
}
}
Run Code Online (Sandbox Code Playgroud)
另请注意,我使用了格式说明符%9s.这样,如果用户输入的字符超过9个,则不会覆盖相邻的存储器.您必须为null字符保留数组的最后一个元素,\0因为C中的字符串以\0.