我是一名崭露头角的C程序员,我编写了这个程序来计算第二版K& R 1.5.4的单词。我的if语句有问题吗?代码似乎在不应该增加变量时增加,因为它不符合初始测试。
#include <stdio.h>
#define IN 1
#define OUT 0
main()
{
int word, state, c;
word = state = OUT;
while((c = getchar()) != EOF)
{
if(c != ' ' || c != '\n' || c != '\t')
{
if(state == OUT)
{
word++;
state = IN;
}
/*else
{
state = IN;
}*/
}
if(c == ' ' || c == '\n' || c == '\t')
{
state = OUT;
}
printf("char: %c %x | state: %d | word: %d\n", c, c, state, word);
}
printf("\n//maniac: %d\n", word);
这导致:
>count_word_my.exe
Hello he he
char: H 48 | state: 1 | word: 1
char: e 65 | state: 1 | word: 1
char: l 6c | state: 1 | word: 1
char: l 6c | state: 1 | word: 1
char: o 6f | state: 1 | word: 1
char: 20 | state: 0 | word: 1
char: 20 | state: 0 | word: 2
char: h 68 | state: 1 | word: 3
char: e 65 | state: 1 | word: 3
char: 20 | state: 0 | word: 3
char: 20 | state: 0 | word: 4
char: 20 | state: 0 | word: 5
char: h 68 | state: 1 | word: 6
char: e 65 | state: 1 | word: 6
char:
a | state: 0 | word: 6
char:
a | state: 0 | word: 7
//maniac: 7
我修改过的K&amp; R代码:
#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
/* count lines, words, and characters in input */
main()
{
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != EOF) {
++nc;
if (c == '\n')
++nl;
if (c == ' ' || c == '\n' || c == '\t')
state = OUT;
else if (state == OUT) {
state = IN;
++nw;
}
printf("char: %c %x | state: %d | word: %d\n", c, c, state, nw);
}
printf("%d %d %d\n", nl, nw, nc);
}
K&amp; R代码导致:
>count_word_test.exe
Hello he he
char: H 48 | state: 1 | word: 1
char: e 65 | state: 1 | word: 1
char: l 6c | state: 1 | word: 1
char: l 6c | state: 1 | word: 1
char: o 6f | state: 1 | word: 1
char: 20 | state: 0 | word: 1
char: 20 | state: 0 | word: 1
char: h 68 | state: 1 | word: 2
char: e 65 | state: 1 | word: 2
char: 20 | state: 0 | word: 2
char: 20 | state: 0 | word: 2
char: 20 | state: 0 | word: 2
char: h 68 | state: 1 | word: 3
char: e 65 | state: 1 | word: 3
char:
a | state: 0 | word: 3
char:
a | state: 0 | word: 3
2 3 16
^C
当代码在第一个if语句中不满足测试时,如何在'Hello'之后处理第二个空格(0x20)时,我的代码如何递增word / nw?即使它确实达到了第二个if语句,我也认为它会将'state'变量设置为1(IN)。我错过了一些关键的东西。我非常感谢给予的任何帮助。谢谢。
答案 0 :(得分:7)
好吧,每个char
都会将此评估为真if(c != ' ' || c != '\n' || c != '\t')
,因为' '
,'\n'
和'\t'
都没有字符。
应该是:
if(c != ' ' && c != '\n' && c != '\t')
答案 1 :(得分:1)
你已经(至少)得到了一个好的答案(我已经投了票)。但请让我详细说明“以防万一”:
if(c == ' ' || c == '\n' || c == '\t') ...
你清楚地理解这一点:如果是“space”或“newline”或“tab”,那么“whitespace == true”。
......但......
if (c != ' ' || c != '\n' || c != '\t') ...
说“如果不是空格......或者不是换行符......或者不是标签”
换句话说,'\ n'会评估为“whitespace == false”...因为'\ n'不是空白,而且它不是标签。
你的真正含义是if (c &= ' ' && c != '\n' && c != '\t') ...
......或if (!(c == ' ' || c == '\n' || c == '\t')) ...
换句话说,问题是“C语法”而不是“布尔逻辑”。
这里有两个简短的教程“沉重的理论”......但你可能会喜欢: