c -我想计数单词,但它不计算单词,一旦它出现在句子中



我想让它计算单词,但是如果这个单词再次出现在句子中,它就不计算了

#include <stdio.h> #include <ctype.h> #include <cs50.h> #include <string.h> #include <math.h>
int main(void){ int letters=0; int words=0; int sentences=0; float L; int S; int W; float z; float 
x;
string para =get_string("Text:");
for(int i=0;i<strlen(para);i++){
if((para[i]>='a' || para[i]<='z') && (para[i]>='A' || para[i]<='Z')
&& (para[i]!=' ') && (para[i]!=',') && (para[i]!='-') && (para[i]!='!')
&& (para[i]!='?') && (para[i]!='.') && (para[i]!=';') && (para[i]!=''')){
L=letters++;
}
if((para[i]==' ') && (para[i]!='.')) { W= words++; }
if((para[i]=='.') || (para[i]=='!') || (para[i]=='?')){ S= sentences++; }
}
L=(float) letters/words * 100; S=(float) sentences/words * 100; //printf("%fn",z); 
//printf("%fn",x);
int index=round(0.0588 * L - 0.296 * S - 15.8); 
if((index==1) || (index==2) || (index==3) || (index==4) || (index==5) || (index==6) || (index==7) 
|| (index==8) || (index==9) || (index==10) || (index==11) || (index==12) || (index==13) || 
(index==14) || (index==15))
{
printf("Grade %in",index); 
}
//printf("letters:%in",letters); //printf("words:%in",words); 
//printf("sentences:%in",sentences); 
if(index>=16)
{
printf("Grade 16+n");
} 
else if(index<1)
{ 
printf("Before Grade 1n"); }
}

下面是输出

Text: would you rather be you.
Grade 5
letters:19
words:4
sentences:1

首先,按照注释部分的说明美化您的代码,以便其他人可以容易地理解这里实现的内容。

第二,这里的用词表里不一不是问题。在您的代码中,您正在计算单词计数的空格。通常,我们可以说两个单词被一个空格隔开,所以总是有一个额外的单词,例如:

I am counting the spaces and the words.

这里的词= 8 &空间= 7

但是如果我在句子中添加了额外的空格,你的代码也会把这个空格算作一个单词。如:

I am counting the spaces    and the words.

这里的话= 8,空格= 10

所以逻辑必须改变。我在此分享一些想法:

1. Check the next letter after getting spaces.
2. If letter then count word.
3. If get '.' then count another word.
4. Skip the signs except '.'.

希望你能得到正确的单词数。

if((para[i]==' ') && (para[i]!='.')) { W= words++; }有问题

如果para[i]==' '是真的,para[i]!='.'也是如此,而不是必要的。

如果para[i]==' '为假,则不需要para[i]!='.'

代码与

相同
if(para[i] == ' ') W = words++;

注意W从未被使用过。


我怀疑OP想要

if((para[i]==' ') || (para[i]=='.')) { W= words++; }


对于我来说,我会根据非字母后跟字母来计数

char previous = 'n';
for (size_t i=0; para[i]; i++) {
if (!isalpha(previous) && isalpha(para[i])) words++;
previous = para[i];
} 

其他问题也存在,但以上解决了OP关注的问题。

最新更新