首页 > 解决方案 > Printf 不一致的结果 [The C Programming Language - Chapter 1.6 Arrays]

问题描述

当运行第 1.6 章 C 编程语言的数组中提供的程序时,我从最终的 printf 中得到了一些非常不一致的结果。

这是程序:

#include <stdio.h>

int main()
{
  int c, i, nwhite, nother;
  int ndigit[10];

  nwhite = nother = 0;

  for (i = 0; i < 10; ++i)
    ndigit[i] = 0;

  while ((c = getchar()) != EOF)
  {
    if (c >= '0' && c <= '9')
        ++ndigit[c-'0'];
    else if (c == ' ' || c == '\n' || c == '\t')
        ++nwhite;
    else
        ++nother;
  }

  printf("digits =");

  for (i = 0; i < 10; ++i)      
    printf(" %d", ndigit[i]);

  printf(" white space = %d \n nother = %d \n", nwhite, nother);
}

这是执行: Windows PowerShell

我对它明显的随机性感到非常困惑。我将非常感谢任何能突出我在这里缺少的东西的人,特别是考虑到这甚至不是我自己制作的程序:这是由本书本身提供的。

谢谢你。


编辑:

我尝试在命令提示符而不是 Windows PowerShell 中运行该程序。结果没有区别。

我也尝试在 main 的开头添加一个 int

  int k = 99;

和两个 printf,之前和之后,最后的 printf

  printf("%d", k);
  printf(" white space = %d \n nother = %d \n", nwhite, nother);
  printf("%d", k);

仅打印两个额外 printf 中的第一个,但代价是中间一个多出 2 个字符。

标签: cprintf

解决方案


推荐阅读