gpt4 book ai didi

c - 如何计算C中相同字符的个数?

转载 作者:太空宇宙 更新时间:2023-11-04 07:44:17 24 4
gpt4 key购买 nike

我正在编写一个提示用户输入字符串的代码

&

创建一个 void 类型的函数,打印出最常用的字符

(因为它出现的次数最多)

&

还显示它在该字符串中出现的次数。

因此,这是我目前所拥有的...

#include <stdio.h>
#include <string.h>
/* frequent character in the string along with the length of the string (use strlen from string.h – this will require you to #include <string.h> at the top of your program).*/


/* Use array syntax (e.g. array[5]) to access the elements of your array.
* Write a program that prompts a user to input a string,
* accepts the string as input, and outputs the most
* You should implement a function called mostfrequent.
* The function prototype for mostfrequent is: void mostfrequent(int *counts, char *most_freq, int *qty_most_freq, int num_counts);
* Hint: Consider the integer value of the ASCII characters and how the offsets can be translated to ints.
* Assume the user inputs only the characters a through z (all lowercase, no spaces).
*/


void mostfrequent(int *counts, char *most_freq, int *qty_most_freq, int num_counts_)
{
int array[255] = {0}; // initialize all elements to 0
int i, index;
for(i = 0; most_freq[i] != 0; i++)
{
++array[most_freq[i]];
}
// Find the letter that was used the most

qty_most_freq = array[0];
for(i = 0; most_freq[i] != 0; i++)
{
if(array[most_freq[i]] > qty_most_freq)
{
qty_most_freq = array[most_freq[i]];
counts = i;
}
num_counts_++;
}
printf("The most frequent character was: '%c' with %d occurances \n", most_freq[index], counts);
printf("%d characters were used \n", num_counts_);
}
int main()
{
char array[5];
printf("Enter a string ");
scanf("%s", array);
int count = sizeof(array);
mostfrequent(count , array, 0, 0);
return 0;
}

我也得到了错误的输出。

输出:

输入字符串你好最常见的字符是:'h',出现 2 次使用了 5 个字符

应该是

出现频率最高的字符是:'l',出现了 2 次使用了 5 个字符

最佳答案

简而言之(如果我写错了其他人会纠正我^_^)你声明一个 int 是这样的:

int var;

像这样使用它:

var = 3;

你像这样声明一个指针:

int* pvar;

并像这样使用指向的值:

*pvar = 3;

如果您声明了一个变量并需要将指针作为函数参数传递给它,请像这样使用 & 运算符:

functionA(&var);

或者简单地将其地址保存在指针变量中:

pvar = &var;

这是基础。我希望它能帮助...

关于c - 如何计算C中相同字符的个数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58174135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com