【问题标题】:Placeholder issue占位符问题
【发布时间】:2020-08-01 03:11:26
【问题描述】:

我想为 int age 使用占位符,但 %i 或 %s 不起作用。

这是我的代码:

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int age = get_int("What is your age ?\n");
    printf("You are %i years old.\n");
}

这是错误:

test1.c:7:22: error: more '%' conversions than data arguments [-Werror,-Wformat]
    printf("You are %i years old.\n");
                    ~^
1 error generated.
<builtin>: recipe for target 'test1' failed
make: *** [test1] Error 1

【问题讨论】:

  • printf("You are %i years old.\n", age);
  • @M.NejatAydin 请将其转换为解释性答案。
  • printf() 和家族中,格式化字符串中的每个% 参数都需要传递一个相应的附加参数,以及该格式规范的数据。如果缺少(如此处),某些编译器会将其视为错误,有些可能会发出警告,有些则忽略(也取决于设置)。可执行的 C 代码在这方面是不可原谅的:没有编译器需要告诉你,并且代码会尝试按照它被告知的去做,无论是否出错。

标签: c printf placeholder cs50


【解决方案1】:

您忘记将age 传递给printf

 printf("You are %i years old.\n", age);
/* Here ---------------------------^ */

【讨论】:

    【解决方案2】:

    您需要为使用的每个“%i”指定要打印的变量。
    像这样:

    #include <stdio.h>
    
    int main()
    {   
        int x = 9;
        int y = 10;
        printf("x = %i, y = %i", x, y);
        return 0;
    }
    

    您也可以将 %d 用于 int 数字。 %s 用于字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-01
      • 1970-01-01
      • 2014-11-24
      • 2014-02-03
      相关资源
      最近更新 更多