printf:未知转换类型字符')'格式为-Wformat

liv*_*hak 2 c random printf

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

rand_distribution.c:24:7: warning: unknown conversion type character ‘)’ in format [-Wformat]
Run Code Online (Sandbox Code Playgroud)

在这条线上

 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%)
Run Code Online (Sandbox Code Playgroud)

也就是说'''之前的'%'应该按原样打印而不被解释.我怎么做到这一点?

#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);
   }
}
Run Code Online (Sandbox Code Playgroud)

小智 8

你需要逃离%标志%%

由于%)不匹配任何变量类型,它都会失败.通过%在它之前添加一个来逃避它.

你的新行应该是,

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

  • 看起来这个答案是在downvotes和comment之后编辑的.如果没有,我不理解downvotes; 答案是多余但正确的. (2认同)