int friends = 20;
printf("I have %d friend%c", friends , (friends !=1 ? "s" : ""));
return 0;
所以每当我运行代码时,它都会调试到这里
I have 20 friend$
当我在 friend
之后使用 %s 格式说明符运行它时,它工作正常。 s
只是一个字符,为什么它不起作用?
最佳答案
那么为什么它不起作用? 因为 %c
需要 char
但表达式 (friends !=1 ? "s ": "")
结果为字符串(双引号)。所以要么使用 %s
这样的
printf("I have %d friend%s", friends , (friends !=1 ? "s" : ""));
或者
将 "s"
替换为 's'
并将 ""
替换为 ' '
as % c
需要 char
。
printf("I have %d friend%c", friends , (friends !=1 ? 's' : ' '));
关于c - c中的格式说明符值问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50104483/