[英]i want to find the frequent letters
在該程序中,我將給出6個名稱,然后我要從整個名稱中查找常用字符。 我試過了,但是除了全名外,沒有顯示所有名稱中的字符。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define max 6
int main()
{
char name[max][20];
char *ptrnaame;
int i,j,len, cnt, k, next, occurence=0, maximum=0;
char *index_max=NULL;
ptrname=name[0];
for(i=0; i<max; i++)
{
printf("Give the name :");
gets(name[i]);
len=strlen(name[i]);
while(len>20)
{
printf("Give the name again:");
gets(name[i]);
}
}
for(i=0; i<max; i++)
{
occurence=0;
for(j=i; j<20; j++)
{
if(!strcmp(*(name+i), *(name+j)))
{
occurence++;
}
}
if(occurence>maximum)
{
maximum=occurence;
index_max=*(name+i);
}
}
if(index_max!=NULL)
{
printf("The most frequent character is: %s with %d occurences", index_max, maximum);
}
system("pause");
return 0;
}
您正在打印字符串( %s
)而不是字符( %c
)。
嘗試這個
printf("The most frequent character is: %c with %d occurences", index_max[0], maximum);
您的程序存在其他人已經指出的錯誤。 最大的錯誤是程序的邏輯不正確。
我認為,如果您的名字是Alice,Bob,Charlie,Dora,Emily和Frank,則您希望輸出為E,這在所有名稱中最常見,即4次。
如果是這樣,那么您必須計算所有字符的出現次數。 有很多可能的方法可以做到這一點。 您可以遍歷所有字母,然后遍歷所有單詞及其字母,並在字母匹配時增加計數。 這很簡單,但是效率很低,因為您將數據處理了26次。
更好的方法可能是保留字母的計數數組。 然后,您只需要檢查一次每個單詞和每個字母:查看字符,如果它是一個字母,則增加相應的計數。
一個不錯的副作用是,現在您不再需要存儲名稱。 當用戶鍵入字母時,讓它們從stdin
流入,對其進行處理並立即將其忽略。 您只對每個字母的總數感興趣。
不存儲名稱也意味着您不再遇到內存管理問題。 例如,在您的原始代碼中,您希望將每個單詞中的字母從0循環到20,但是單詞中不一定有那么多個字母。 char緩沖區僅保留有效輸入,直到終止的空字符為止; 之后的一切都是垃圾。 您還錯誤地將字母索引用作單詞的索引,其中只有六個。 這會導致錯誤的內存訪問。
這是一個示例實現,可讓您輸入任意數量的名稱:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int count[26] = {0}; // counts for 26 letters
char line[80]; // line buffer
int i;
puts("[Please enter text. A blank line or Ctrl-D/Z ends input.]");
while (fgets(line, sizeof(line), stdin)) {
int nonspace = 0;
for (i = 0; line[i] != '\0'; i++) {
int c = line[i];
if ('A' < c && c <= 'Z') count[c - 'A']++;
if ('a' < c && c <= 'z') count[c - 'a']++;
if (c != ' ' && c != '\n') nonspace++;
}
if (nonspace == 0) break;
}
int imax = 0;
for (i = 1; i < 26; i++) {
if (count[i] > count[imax]) {
imax = i;
}
}
printf("Most frequent character is %c (occurs %d times).\n",
'A' + imax, count[imax]);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.