Lv 5
asked in 電腦與網際網路程式設計 · 1 decade ago

c語言[輸入英文字母計算最多字母次數]

[Basic] Array Arguments

Write a funtion majorChar(str[], len) that returns the most frequent character in a character array.

I.e. its return value is a character!

The meaning of the parameters of majorChar() are as follows:

Parameters 參數 Meaning 意義

str[] a character array 存有字元的陣列

len number of characters in this array 陣列中字元個數

In main(), the program takes a message entered by the user and call majorChar() to find the most frequent character.

範例如下 (藍字部份是使用者自己輸入的部份): Example: (Blue text is the input entered by the user)

請輸入一句英文:Harry Potter

出現最多次的字元是 <r> Enter a message: Harry Potter

The most frequent character is <r>

[Hint]

Here provides a brute-force approach:

Run a for-loop from str[0] to str[n] (where n = len -1) to examine each character in the array.

Consider a character str[i], compare it with str[i] up to str[n] so that you will know the frequency of str[i].

Now what you need to do is exactly find the character with the maximal frequency!

Note that instead of passing the size of the character array to function majorChar(),

you only need to pass the number of characters in the array.

You can know the number when getting input from the user.

2 Answers

Rating
  • Thomas
    Lv 6
    1 decade ago
    Favorite Answer

    #include <stdio.h>

    #include <stdlib.h>

    #include <string.h>

    #include <conio.h>

    char majorChar(char str[], int len)

    {

    char maxCh='\r';

    int maxCount=-1, temp, i, j;

    for (i=0;i<len;i++)

    {

    temp=1;

    for (j=i+1;j<len;j++)

    if(str[i]==str[j])temp++;

    if (temp>maxCount)

    {

    maxCh = str[i];

    maxCount=temp;

    }

    }

    return maxCh; //return '\r',表示 null string

    }

    int main()

    {

    char str[1000]; //最多1000字元

    int len;

    printf("請輸入一句英文:");

    //為了要讀' ',改用getch()

    len=0;

    while ( (str[len]=getch())!='\r')

    {

    putch(str[len]);//echo input

    len++;

    }

    printf("\n");

    if (len==0)

    printf("輸入空字串\n");

    else

    printf("出現最多次的字元是<%c>\n", majorChar(str,len));

    system("pause");

    return 0;

    }

  • 1 decade ago

    我感覺這個英文比c還難

    你不如先翻譯成中文

Still have questions? Get your answers by asking now.