当我尝试编译此代码时,我不断收到此错误:
#include <stdio.h>
int main(void)
{
int userInt;
int x;
double userDouble;
char userChar;
char userString[20];
printf("%d", "%lf", "%c", "%s", userInt, userDouble, userChar, userString);
}
谁能提供一些见解?
最佳答案
您正在 print()
的 first 参数中传递 "%d"
,因此它(以及编译器,因为您是显然,使用在编译时验证 printf 样式参数的参数)会将第二个参数解释为整数,但您在中传递“%lf”
第二个参数。字符串文字在 C 中是 char[]
,在 C++ 中是 const char[]
,并且会衰减为 char*
和 >const char*
分别。因此出现错误。
您只需将所有格式说明符放在第一个参数中,例如:
printf("%d %lf %c %s", userInt, userDouble, userChar, userString);
或者,如果您确实想在输出中用引号和逗号分隔值:
printf("\"%d\", \"%lf\", \"%c\", \"%s\"", userInt, userDouble, userChar, userString);
关于c - "Error: format ‘%d’ 需要类型为 ‘int’ 的参数,但参数 2 的类型为 ‘char *’ ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52488535/