字母数的单词频率(仅基本循环)。

问题描述 投票:0回答:1

我想写一个C程序,用基本的循环技术来打印单词的长度和它们的频率。我可以得到单词长度的工作,但我坚持频率(例如。Do 2 not 3 judge 5 a 1 book 4 (曾解决这个问题)

  • 有#个单词含有1个字母
  • 有#个单词包含2个字母

等...

#include <stdio.h>
int main(void) {

char word[30];
int i = 0,b=0,c=0,j=0,d=0;
printf("Please enter a word: ");

for (i = 0; i < 30 ; i++){
    scanf("%s", word);           
          while (word[b]!='\0'){ 
              b++;  
          }   
    printf("%s %d ", word, b);
    b = 0;
}

return 0;  
}
c loops frequency
1个回答
1
投票

你的问题并不完全清楚。但根据我的理解,你还想打印次数(频率)长度为''的字。l'是由用户输入的。因此,我将回答。

你可以直接 存词 在用户输入的数组中。一旦所有的输入都被读取,你就可以从存储的数组中打印出每个字长的频率。

请参考下面的代码来理解我的意思。

#include <stdio.h>
int main(void) {

char word[30];
int i = 0,b=0,c=0,j=0,d=0;
int word_length_freq[30]={0};       //an array which will store the frequency of word length(all initialized to 0)
                                   //eg. if word is "hello" it will increase count of word_length_freq[5] by 1
printf("Please enter a word: ");

for (i = 0; i < 3 ; i++){
    scanf("%s", word);           
          while (word[b]!='\0'){ 
              b++;  
          }   
    word_length_freq[b]++;
    printf("%s %d ", word, b);    
    b = 0;
}

for(int i=1;i<30;i++){          //This will print the frequency of all words from length 1 to 30
    printf("There are %d words of length %d\n",word_length_freq[i],i);
}

return 0;  
}

希望这能解决你的问题!

© www.soinside.com 2019 - 2024. All rights reserved.