【问题标题】:How do I display variables in C printf() functions?如何在 C printf() 函数中显示变量?
【发布时间】:2014-02-09 02:16:28
【问题描述】:

我尝试在下面的 printf() 函数中打印两个整数值:

printf("%s", "The quotient is %d with remainder %d", quo, rem);

我的书说这应该打印

The quotient is 5 with remainder 1

quo 是 11 和 rem 1),但它会打印

The quotient is %d with remainder %d

我正在使用 gcc 编译和运行 Ubuntu 12.04 LTS(64 位)。我看错了吗?是编译器的问题吗?

【问题讨论】:

    标签: c integer printf


    【解决方案1】:

    你的格式字符串太多了。您应该使用:

    printf("The quotient is %d with remainder %d\n", quo, rem);
    

    注意最后的换行符。否则,您可能无法及时看到输出。

    如果这本书有这个错误,并且它不包含换行符,那么我认为你应该决定放弃这本书并获得更好的。

    你得到的输出是预期的。 "%s" 表示“将下一个参数作为字符串并打印出来”;额外的参数(quorem)会被忽略。

    【讨论】:

      【解决方案2】:

      您误解了printf 的工作原理。只有第一个参数被解析为格式字符串,所以%s直接替换为给定的字符串,包括%d的。

      正确的形式是printf("The quotient is %d with remainder %d\n", quo, rem);

      【讨论】:

        【解决方案3】:

        应该是

        printf("The quotient is %d with remainder %d", quo, rem);

        第一个参数是要打印的模式,因此您正在打印

        "The quotient is %d with remainder %d" 作为纯字符串 (%s)。

        请注意,printf 中的额外参数会被忽略,因此您的解决方案中会忽略 quorem

        【讨论】:

          【解决方案4】:

          朋友,试试这个

          printf("The quotient is %d with remainder %d", quo, rem);
          

          第一个参数应该是格式字符串。在您的情况下,当您希望它是“商是 %d 余数 %d”时,它是错误的“%s”

          【讨论】:

            【解决方案5】:

            printf() 中的第一个参数是格式字符串。当你这样做时

            printf("%s", "The quotient is %d with remainder %d", quo, rem);
            

            格式字符串是“%s”而不是“商是 %d 余数 %d”。

            你应该这样做

                printf("The quotient is %d with remainder %d", quo, rem);
            

            【讨论】:

              猜你喜欢
              • 2020-08-23
              • 1970-01-01
              • 2013-09-14
              • 1970-01-01
              • 2013-01-10
              • 1970-01-01
              • 2021-04-07
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多