【问题标题】:Words frequency with number of letters (basic loop only)单词频率与字母数量(仅限基本循环)
【发布时间】:2020-05-29 20:43:52
【问题描述】:

我想用基本的循环技术编写 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;  
}

【问题讨论】:

  • 我不清楚你对频率部分的要求是什么,你能举个例子吗?
  • 有 1 个单词有 1 个字母 // a 有 1 个单词有 2 个字母 // 有没有 1 个单词有 3 个字母 // 不是
  • int count[MAX_WORD_LENGTH] = {0}; 然后是您的代码,只需在循环内的printf() 调用之后立即添加count[b]++;;最后,打印这个新数组的内容。
  • 但我只想要基本循环,没有任何功能或算法
  • 这是我看不懂的解决方案i.postimg.cc/SNqxfy3y/1.png

标签: c loops frequency


【解决方案1】:

您的问题并不完全清楚。但据我了解,您还想打印用户输入长度为 'l' 的单词的次数(frequency)。所以我会回答:

您可以将单词的长度存储在用户输入的数组中。读取所有输入后,您可以从存储的数组中打印每个字长的频率

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

#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;  
}

我希望这能解决你的问题!

【讨论】:

  • 这是我看不懂的解决方案i.postimg.cc/SNqxfy3y/1.png
  • @Florian 你对此有什么疑问?
  • 毫无疑问只是我看不懂,所以我搜索了更简单的解决方案,至少对我来说,您似乎更容易理解,所以谢谢
  • 谢谢。补充一点,在这两种解决方案中,存储频率的数组在读取每个单词后都会递增 1,递增的 index 是单词的长度。我还在我的解决方案中留下了一个例子。
猜你喜欢
  • 1970-01-01
  • 2022-11-22
  • 2017-09-27
  • 2019-02-01
  • 1970-01-01
  • 2019-07-07
  • 2016-09-01
  • 2018-04-15
  • 1970-01-01
相关资源
最近更新 更多