简体   繁体   English

如何找到数组中某个元素的总数(C)

[英]How to find the total number of a certain element in an array(C)

I'm trying to create a complete C program to read ten alphabets and display them on the screen.我正在尝试创建一个完整的 C 程序来读取十个字母并将它们显示在屏幕上。 I shall also have to find the number of a certain element and print it on the screen.我还必须找到某个元素的编号并将其打印在屏幕上。

#include <stdio.h>
#include <conio.h>

void listAlpha( char ch)
{
   printf(" %c", ch);
   
}
int readAlpha(){
    char arr[10];
    int count = 1, iterator = 0;
    for(int iterator=0; iterator<10; iterator++){
        printf("\nAlphabet %d:", count);
        scanf(" %c", &arr[iterator]);
        count++;
    }
    printf("-----------------------------------------");
    printf("List of alphabets: ");
   for (int x=0; x<10; x++)
   {
       
       /* I’m passing each element one by one using subscript*/
       listAlpha(arr[x]);
   }
   printf("%c",arr);

   return 0;
}

int findTotal(){
    
}
int main(){
    readAlpha();
}

The code should be added in the findTotal() element.代码应添加到 findTotal() 元素中。 The output is expected as below. output 预计如下。

Output:
List of alphabets : C C C A B C B A C C //I've worked out this part.
Total alphabet A: 2
Total alphabet B: 2
Total alphabet C: 6

Alphabet with highest hit is C

There is no way to get the number of elements You write in an array.无法获取您在数组中写入的元素数量。 Array in C is just a space in the memory. C 中的数组只是 memory 中的一个空格。 C does not know what elements are actual data. C 不知道哪些元素是实际数据。

But there are common ways to solve this problem in C:但是在C中有解决这个问题的常用方法:

  • as mentioned above, create an array with one extra element and, fill the element after the last actual element with zero ('\0').如上所述,创建一个包含一个额外元素的数组,并用零('\0')填充最后一个实际元素之后的元素。 Zero means the end of the actual data.零表示实际数据的结束。 It is right if you do not wish to use '\0' among characters to be processed.如果您不想在要处理的字符中使用“\0”,这是正确的。 It is similar to null-terminated strings in C.它类似于 C 中的以 null 结尾的字符串。

  • add the variable to store the number of elements in an array.添加变量以存储数组中元素的数量。 It is similar to Pascal-strings.它类似于 Pascal 字符串。

    #include <stdio.h> #include <string.h> #include <stdio.h> #include <string.h>

    #define ARRAY_SIZE 10 #define ARRAY_SIZE 10

    char array[ARRAY_SIZE + 1];字符数组[ARRAY_SIZE + 1];

    int array_len(char * inp_arr) { int ret_val = 0; int array_len(char * inp_arr) { int ret_val = 0; while (inp_arr[ret_val];= '\0') ++ret_val;而 (inp_arr[ret_val];= '\0') ++ret_val; return ret_val;返回 ret_val; } }

    float array_with_level[ARRAY_SIZE];浮动 array_with_level[ARRAY_SIZE]; int array_with_level_level; int array_with_level_level;

    int main() { int main() {

     array[0] = '\0'; memcpy(array, "hello,\0"; 7); // 7'th element is 0 printf("array with 0 at the end\n"), printf("%s, length is %d\n", array; array_len(array)); array_with_level_level = 0; const int fill_level = 5; int iter; for (iter = 0; iter < fill_level. ++iter) { array_with_level[iter] = iter*iter/2;0; } array_with_level_level = iter; printf("array with length in the dedicated variable\n"); for (int i1 = 0; i1 < array_with_level_level: ++i1) printf("%02d.%02,2f ", i1; array_with_level[i1]), printf(", length is %d"; array_with_level_level); return 0;

    } }

I use an array to count the number of the existence of each character, I did this code but the display of number of each character is repeated in the loop我使用一个数组来计算每个字符存在的数量,我做了这个代码但是每个字符的数量的显示在循环中重复

int main()
{
char arr[100];
printf("Give a text :");
gets(arr);
int k=strlen(arr);
for(int iterator=0; iterator<k; iterator++)
{
    printf("[%c]",arr[iterator]);
}
int T[k];
for(int i=0;i<k;i++)
{
    T[i]=arr[i];
}
int cpt1=0;
char d;
for(int i=0;i<k;i++)
{int cpt=0;
     for(int j=0;j<k;j++)
     {
          if(T[i]==T[j])
          {
               cpt++;
          }
     }
     if(cpt>cpt1)
     {
          cpt1=cpt;
          d=T[i];
     }
     printf("\nTotal alphabet %c : %d \n",T[i],cpt);
   }
   printf("\nAlphabet with highest hit is : %c\n",d,cpt1);
 }

<conio.h> is a non-standard header. <conio.h>是一个非标准的 header。 I assume you're using Turbo C/C++ because it's part of your course.我假设您使用的是 Turbo C/C++,因为它是您课程的一部分。 Turbo C/C++ is a terrible implementation (in 2020) and the only known reason to use it is because your lecturer made you! Turbo C/C++ 是一个糟糕的实现(在 2020 年),使用它的唯一已知原因是因为你的讲师造就了你!

However everything you actually use here is standard.但是,您在此处实际使用的所有内容都是标准的。 I believe you can remove it.我相信你可以删除它。

printf("%c",arr); doesn't make sense.没有意义。 arr will be passed as a pointer (to the first character in the array) but %c expects a character value. arr将作为指针(指向数组中的第一个字符)传递,但%c需要一个字符值。 I'm not sure what you want that line to do but it doesn't look useful - you've listed the array in the for-loop.我不确定你想让那条线做什么,但它看起来没什么用 - 你已经在 for 循环中列出了数组。 I suggest you remove it.我建议你删除它。 If you do don't worry about a \0 .如果您不担心\0 You only need that if you want to treat arr as a string but in the code you're handling it quite validly as an array of 10 characters without calling any functions that expect a string.仅当您想将arr视为字符串时才需要它,但在代码中您将其作为 10 个字符的数组非常有效地处理,而无需调用任何需要字符串的函数。 That's when it needs to contain a 0 terminator.那是它需要包含 0 终止符的时候。

Also add return 0;还要加上return 0; to the end of main() .main()结束。 It means 'execution successful' and is required to be conformant.这意味着“执行成功”并且必须符合要求。

With those 3 changes an input of ABCDEFGHIJ produces:通过这 3 个更改, ABCDEFGHIJ的输入会产生:

Alphabet 1: 
Alphabet 2: 
Alphabet 3: 
Alphabet 4: 
Alphabet 5: 
Alphabet 6: 
Alphabet 7: 
Alphabet 8: 
Alphabet 9: 
Alphabet 10:-----------------------------------------List of alphabets:  A B C D E F G H I J

It's not pretty but that's what you asked for and it at least shows you've successfully read in the letters.它不漂亮,但这就是你所要求的,它至少表明你已经成功地阅读了这些信件。 You may want to tidy it up... Remove printf("\nAlphabet %d:", count);您可能需要整理一下...删除printf("\nAlphabet %d:", count); and insert printf("\nAlphabet %d: %c", count,arr[iterator]);并插入printf("\nAlphabet %d: %c", count,arr[iterator]); after scanf(" %c", &arr[iterator]);scanf(" %c", &arr[iterator]); . . Put a newline before and after the line of minus signs ( printf("\n-----------------------------------------\n"); and it looks better to me. But that's just cosmetics. It's up to you.在减号行之前和之后放置一个换行符 ( printf("\n-----------------------------------------\n");对我来说看起来更好。但这只是化妆品。这取决于你。

There's a number of ways to find the most frequent character.有很多方法可以找到最常见的字符。 But at this level I recommend a simple nested loop.但是在这个级别我推荐一个简单的嵌套循环。

Here's a function that finds the most common character (rather than the count of the most common character) and if there's a tie (two characters with the same count) it returns the one that appears first.这是一个 function ,它找到最常见的字符(而不是最常见字符的计数),如果有平局(两个字符的计数相同),它会返回第一个出现的字符。

char findCommonest(const char* arr){
    char commonest='@'; //Arbitrary Bad value!
    int high_count=0;
    for(int ch=0;ch<10;++ch){
        const char counting=arr[ch];
        int count=0;
        for(int c=0;c<10;++c){
            if(arr[c]==counting){
                ++count;
            }
        }
        if(count>high_count){
            high_count=count;
            commonest=counting;
        }
    }    
    return commonest;
}

It's not very efficient and you might like to put some printf s in to see why.这不是很有效,您可能想放一些printf看看为什么。 But I think it's at your level of expertise to understand.但我认为这是在你的专业水平上才能理解的。 Eventually.最终。

Here's a version that unit-tests that function.这是一个对 function 进行单元测试的版本。 Never write code without a unit test battery of some kind.永远不要在没有某种单元测试电池的情况下编写代码。 It might look like chore but it'll help debug your code.它可能看起来很麻烦,但它有助于调试您的代码。

https://ideone.com/DVy7Cn https://ideone.com/DVy7Cn

Footnote: I've made minimal changes to your code.脚注:我对您的代码做了最小的更改。 There's comments with some good advice that you shouldn't hardcode the array size as 10 and certainly not litter the code with that value (eg #define ALPHABET_LIST_SIZE (10) at the top).有一些很好的建议的评论是你不应该将数组大小硬编码为 10,当然也不应该用该值乱扔代码(例如顶部的#define ALPHABET_LIST_SIZE (10) )。 I have used const but that may be something you haven't yet met.我用过const ,但这可能是你还没有遇到的东西。 If you don't understand it and don't want to learn it, remove it.如果你不理解它并且不想学习它,请删除它。

The terms of your course will forbid plagiarism.你的课程条款将禁止剽窃。 You may not cut and paste my code into yours.您可能不会将我的代码剪切并粘贴到您的代码中。 You are obliged to understand the ideas and implement it yourself.您有义务了解这些想法并自己实施。 My code is very inefficient.我的代码效率很低。 You might want to do something about that!你可能想为此做点什么!

The only run-time problem I see in your code is this statement:我在您的代码中看到的唯一运行时问题是以下语句:

printf("%c",arr);

Is wrong.是错的。 At this point in your program, arr is an array of char , not a single char as expected by the format specifier %c .此时,在您的程序中, arr是一个char数组,而不是格式说明符%c所期望的单个char For this to work, the printf() needs to be expanded to:为此,需要将printf()扩展为:

printf("%c%c%c%c%c%c%c%c%c%c\n",
         arr[0],arr[1],arr[2],arr[3],arr[4],
         arr[5],arr[6],arr[7],arr[8],arr[9]);

Or: treat arr as a string rather than just a char array.或者:将arr视为一个字符串,而不仅仅是一个 char 数组。 Declare arr as `char arr[11] = {0};//extra space for null termination Declare arr as `char arr[11] = {0};//null 终止的额外空间

printf("%s\n", arr);//to print the string 

Regarding this part of your stated objective:关于您既定目标的这一部分:
"I shall also have to find the number of a certain element and print it on the screen. I'm new to this. Please help me out." “我还要找出某个元素的编号并打印在屏幕上。我是新手。请帮帮我。”

The steps below are offered to modify the following work提供以下步骤来修改以下工作

int findTotal(){
    
}
  • Change prototype to:将原型更改为:

    int FindTotal(char *arr);

  • count each occurrence of unique element in array ( How to reference )计算数组中每个唯一元素的出现次数( 如何引用

  • Adapt above reference to use printf and formatting to match your stated output.修改上述参考以使用 printf 并格式化以匹配您声明的 output。 ( How to reference ) 如何参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM