【问题标题】:C - format specifies type int but the argument has type long [closed]C - 格式指定类型 int 但参数的类型为 long [关闭]
【发布时间】:2015-06-10 20:26:01
【问题描述】:

我找不到如何解决这个练习:它是关于学习字符计数(我使用的是 Kernighan-Ritchie 版本)。我的问题栏说:

warning: format specifies type 'int' but the argument has type 'long' [-Wformat]
    printf("%1d\n", nc);
            ^  %1ld

这是代码:

#include <stdio.h>

int main()
{
    long nc;

    nc = 0;
    while (getchar() != EOF)
        ++nc;
    printf("%1d\n", nc);
}

我在 Mac 上使用 Qt Creator 3.1.1。 Xcode 版本 6.2 (6C131e) 上的相同问题。

有什么帮助吗?提前致谢。

【问题讨论】:

  • This printf reference 可能会在未来出现。
  • 你看错了1l
  • @BLUEPIXY , 1 不需要吧?
  • @CoolGuy 我认为这不需要计算字符数的结果。

标签: c types arguments long-integer


【解决方案1】:

long 的正确格式说明符是 %ld,而不是 %d。 (%d 需要 int。)

要解决问题,请替换

printf("%1d\n", nc);

printf("%ld\n", nc);

【讨论】:

  • 谢谢,这正是我想要的。
  • 只需使用"%ld"1 几乎可以肯定是一个错误,"%1ld" 是多余且令人困惑的。
  • @chqrlie ,因为一个数字至少有一个字符长对吧?
  • 是的,除非精度为 0,否则转换至少会产生 1 个字符。唯一的例外是:printf("%.0d", 0); 不产生任何字符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-28
  • 2020-08-02
  • 2014-04-23
  • 1970-01-01
  • 1970-01-01
  • 2017-09-04
  • 1970-01-01
相关资源
最近更新 更多