【问题标题】:My C arrays test program is not working [closed]我的 C 数组测试程序不工作 [关闭]
【发布时间】:2015-02-24 20:52:16
【问题描述】:

我正在阅读 The C Programming Language 2nd Edition。我在教程介绍中做 2.10。我必须编写一个关于数组的程序。它应该计算数字、空格和其他。这是程序:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
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, other = %d\n", nwhite, nother);
return 0;
}

按照书上的说法,程序本身的输出是

数字 = 9 3 0 0 0 0 0 0 0 1,空格 = 123,其他 = 345

我有两个问题:

  1. 如果我不按 CTRL+Z,程序将如何自行输出?
  2. 当我手动执行时,输出不正确。请查看我是否在代码中犯了错误。

我得到的输出是

数字 =,空格 = 0,其他 = 0

【问题讨论】:

  • 1)prog &lt; prog.c 2)i &lt; 0 --> i &lt; 10
  • 编译所有警告和调试信息(例如gcc -Wall -Wextra -g,如果使用GCC...)然后使用调试器(例如gdb)。这是一项必不可少的技能。
  • 我在调试器或构建文件中没有错误。我正在使用代码块
  • @UddhavaSwaminathan:那么请去寻求有关您故障调试器的帮助;很明显你非常需要它。别再骂钉子了;修好锤子!
  • @Ruud 他可能假设调试器是一个程序,它为您提供代码中的问题列表。 :-)

标签: c


【解决方案1】:
for (i = 0; i < 0; ++i)

这是错误的。

【讨论】:

  • 请输入正确的代码
  • @UddhavaSwaminathan 不,我让它作为练习。
  • It is i
  • 不,倒数第四行是i&lt;0
  • 它给出的输出与书中给出的相似,但不是正确的
【解决方案2】:

这个:

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

for 循环的标头中有一个损坏的中间部分; i &lt; 0 不会是真的(永远!)所以循环不会运行。

【讨论】:

  • It is i
  • 查看你的最后一个 for 循环
  • 请停止回答这个问题。感谢您的帮助
  • i 是一个有符号整数,所以最终它会停止(好吧,除非循环的内容不会使其过早崩溃)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-10
  • 2011-08-06
  • 1970-01-01
  • 1970-01-01
  • 2011-06-04
相关资源
最近更新 更多