【问题标题】:How do I align my last column according the the column using Printf如何使用 Printf 根据列对齐我的最后一列
【发布时间】:2021-11-19 06:07:29
【问题描述】:

我在尝试使用 C 编程根据第三列标题对齐最后一列数字时遇到问题。我想将一列的宽度设置为 15 个字符。任何想法将不胜感激。

printf("%-15s ", "Fahrenheit     Celsius        Kelvin         \n");
printf("---------------------------------------------\n");    
printf("%-15d""%.2f           %-.2f           \n", fahrenheit, celsius, kelvin);

我的输出如下所示:

【问题讨论】:

标签: c formatting printf


【解决方案1】:

使用 width 和 打印说明符。

还要考虑 "-" flag 与打印说明符以左对齐输出。

  int fahrenheit = 0;
  double celsius = (fahrenheit - 32.0) / (180 / 100.0);
  double kelvin = celsius + 273.15;

  int width_f = 15;  // Adjust widths as desired
  int width_c = 12;
  int width_k = 12;
  int line_n = width_f + 1 + width_c + 1 + width_k;
  char line[line_n + 1]; // VLA
  memset(line, '-', line_n);
  line[line_n] = '\0';

  printf("%*s %*s %*s\n", //
      width_f, "Fahrenheit", width_c, "Celsius", width_k, "Kelvin");
  printf("%s\n", line);
  printf("%*d %*.2f %*.2f\n", //
      width_f, fahrenheit, width_c, celsius, width_k, kelvin);

输出

     Fahrenheit      Celsius       Kelvin
-----------------------------------------
              0       -17.78       255.37

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-12
    • 2019-06-07
    • 1970-01-01
    • 2011-05-22
    • 2013-12-09
    • 2014-12-18
    • 2022-01-01
    • 2021-05-31
    相关资源
    最近更新 更多