【问题标题】:printf: unknown conversion type character ')' in format -Wformat [duplicate]printf:未知转换类型字符')',格式为-Wformat [重复]
【发布时间】:2013-08-08 22:44:39
【问题描述】:

我编写了一个 C 程序,它给出了以下编译错误。

rand_distribution.c:24:7: warning: unknown conversion type character ‘)’ in format [-Wformat]

在这一行

 printf("%d: %d (%.2lf %) \n", i+1, frequencies[i],100.0 * frequencies[i] / TOTAL_COUNT);

My objective to get an output like this.
1: 333109 (16.66%)
2: 333113 (16.66%)
3: 333181 (16.66%)
4: 333562 (16.68%)
5: 333601 (16.68%)
6: 333434 (16.67%)

也就是说 ')' 之前的 '%' 应该按原样打印而不被解释。我该如何实现呢?

#include <stdio.h>
#include <stdlib.h>  // for rand(), srand()
#include <time.h>    // for time()

const int TOTAL_COUNT = 2000000;  // Close to INT_MAX
const int NUM_FACES = 6;
int frequencies[6] = {0}; // frequencies of 0 to 5, init to zero

int main()
{
   srand(time(0)); /* seed random number generator with current time*/

   /* Throw the die and count the frequencies*/
   int i = 0;
   for (i = 0; i < TOTAL_COUNT; ++i)
   {
      ++frequencies[rand() % 6];
   }

   /*Print statisics*/
   for (i = 0; i < NUM_FACES; i++)
   {
      printf("%d: %d (%.2lf %) \n", i+1, frequencies[i],100.0 * frequencies[i] / TOTAL_COUNT);
   }
}

【问题讨论】:

    标签: c random printf


    【解决方案1】:

    您需要转义% 符号%%

    由于%) 不匹配任何变量类型,它会失败。通过在它前面添加 % 来转义它。

    你的新行应该是,

    printf("%d: %d (%.2lf %%) \n", i+1, frequencies[i],100.0 * frequencies[i] / TOTAL_COUNT);
    

    【讨论】:

    • 不。 % 是一个以不同方式转义的字符。
    • 看起来这个答案是在反对和评论后编辑的。如果不是,我不理解反对票;答案是多余但正确的。
    • @Dogbert 什么?我错了吗?
    • @KeithThompson 你是对的。此答案已更正,但最初不正确(初始:\%,编辑后:%%)。
    • @KeithThompson 我明白发生了什么,是的,第一个答案是错误的。
    【解决方案2】:

    要打印带有printf 的%,请使用%% 转换规范。

    替换

    printf("%d: %d (%.2lf %) \n"
    

    与

    printf("%d: %d (%.2lf %%) \n"
    

    要了解为什么\% 不起作用,请参阅 c-faq 问题:

    “问:如何在 printf 格式字符串中打印 '%' 字符?我尝试了 \%,但没有成功。”

    http://c-faq.com/stdio/printfpercent.html

    【讨论】:

      【解决方案3】:

      如果你想打印%。你应该写%%

      :

      printf("%d: %d (%.2lf %%) \n"
      

      【讨论】:

        【解决方案4】:

        使用%% 转义字符。

        例如:printf("Percent%%") 产生“百分比”。

        因此,在您的情况下,您的格式字符串应类似于 printf("%d: %d (%.2lf%%) \n",...)

        参考资料:


        1. How to escape the % sign in C's printf?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-22
          • 1970-01-01
          • 1970-01-01
          • 2018-04-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多