具体公式: 编写一个程序,计算输入行中的单词数。在word中表示一致性,第一个字符必须是字母。
输入和输出示例:
输入:一2二三
输出:2
输入:一二三四五六六
输出:5
输入:789878moer 及更多
输出:2
输入:类似于 8this
输出:2
程序:
#include <stdio.h>
#define YES 1
#define NO 0
int main() {
int c, nw, inword, first_char;
inword = first_char = NO;
nw = 0;
while((c = getchar()) != EOF) {
if (c == ' ' || c == '\n' || c == '\t') {
inword = first_char = NO;
} else if (inword == NO && first_char == NO) {
if ((65 < c && c < 90) || (97 < c && c < 122)) {
++nw;
inword = YES;
} else {
first_char = YES;
}
}
}
printf("%d\n", nw);
}
答案:
- 这是正确的解决方案吗?
- 是否可以以更优雅的方式决定这项任务?如果是,如何?
最佳答案
Is it correct solution?
我测试了一些案例,对我来说似乎没问题。
Is it possible to decide this task in more elegant way? If yes, How?
下面一行
if((65 < c && c < 90) || (97 < c && c < 122))
使用魔数(Magic Number)和 ASCII 值来检查是否 c
是一个字母表。
您可以使用库函数 isalpha()
定义于 <ctype.h>
头文件,使上面的行变成:
if (isalpha(c))
关于计算输入行中的单词数。其中单词只是一致性,第一个字符只是字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51962235/