我的printf输出有什么问题?

时间:2015-12-05 02:36:25

标签: c debugging

无法调试我在oct-nov和nov-dec之间获得空格的原因。这是代码:

if (month == 1)
printf("jan");

if (month == 2)
printf("feb");

 if (month == 3)
 printf("march");

if (month == 4)
printf("apr");

if (month == 5)
printf("may");

if (month == 6)
printf("jun");

if (month == 7)
printf("jul");

if (month == 8)
printf("aug");

if (month == 9)
printf("sept");

if (month == 10)
printf("oct");

if (month == 11)
printf("nov");

if (month == 12)
printf("dec");



printf(" %c       | %.1f | %.1f | %.1f | %.1f     |\n", month, monthly->maxTemperature,
monthly->minTemperature, monthly->averageTemperature, monthly->totalPrecipitation);

也试过改变间距,但由于某种原因,它总是在这两个月之间。谢谢!

编辑:

它是此功能的一部分:

void printMonthlyStatistic(int month,const struct MonthlyStatistic*   monthly)

并在主程序中调用,如下所示:

 for(i=0;i<12;i++){
   printMonthlyStatistic(i+1,&monthly[i])

我的示例输出:

|   Month   | High  |  Low  |  Avg  | Precip  |
|-----------|-------|-------|-------|---------|
jan        | 9.8 | -26.2 | -7.8 | 55.3     |
feb        | 7.5 | -23.3 | -8.6 | 33.1     |
march        | 14.2 | -19.6 | -4.7 | 33.2     |
apr        | 23.7 | -5.3 | 6.2 | 56.8     |
may        | 33.0 | -0.6 | 13.9 | 62.7     |
jun        | 32.1 | 8.0 | 19.7 | 69.7     |
jul        | 34.9 | 12.6 | 22.2 | 181.8     |
aug       | 31.5 | 11.0 | 20.9 | 69.2     |
 sept          | 34.1 | 5.0 | 16.1 | 69.0     |
oct 
   | 24.8 | -2.9 | 10.8 | 56.9     |
nov 
       | 16.0 | -12.8 | 2.1 | 36.2     |
dec 
       | 15.6 | -17.8 | -4.2 | 65.8     |

2 个答案:

答案 0 :(得分:2)

%c打印带有指定charcode的字符,如果使用ASCII代码,则10为换行符,11为垂直制表符。

此外,您应该使用数组而不是编写太多if s。

试试这个:

static const char *month_names[] = {"jan", "feb", "march", "apr", "may", "jun", "jul", "aug", "sept", "oct", "nov", "dec"};
printf("%-11s| %.1f | %.1f | %.1f | %.1f     |\n",
  1 <= month && month <= 12 ? month_names[month - 1] : "", monthly->maxTemperature,
  monthly->minTemperature, monthly->averageTemperature, monthly->totalPrecipitation);

答案 1 :(得分:1)

您的问题是打印字符的%c。 ASCII值NewLine为10,Vertical Tab为11: enter image description here