gpt4 book ai didi

c - 显示最少/最常出现的字符的程序

转载 作者:太空宇宙 更新时间:2023-11-04 04:33:15 25 4
gpt4 key购买 nike

我刚刚编写了应该显示最多/最少(取决于开关选择)出现字符的代码。它必须使用标准输入,即来自键盘以及文本文件的输入。显示最常出现的所有字符对于该程序至关重要。例如在输入“abbcc”中它应该显示 b 和 c。它运行,但不显示字符。问题是:为什么?

代码如下:

一)主要

int main (int argc, char *argv[]) {
int string;
int allChars[256] = {0};
while ( (string=getchar())!=EOF )
allChars[string]++;
if (argc < 2)
mostOften(allChars);
else {
switch (argv[1][1]) {
case 'm': case 'M':
mostOften(allChars);
break;
case 'l': case 'L':
leastOften(allChars);
break;
default:
mostOften(allChars);
break;
} //switch
} // else
} // main

b) sf.c

void mostOften(int *s) {
int i, j;
int max[256] = {0} ;
int max_count = 1;
for (i=0; i<256; i++) {
if (s[i]) {
if (s[i] > max_count) {
for (j=0; j<256; j++)
max[j]=0;
max[i]=1;
max_count = s[i];
} // 2nd_if
else if (s[i] == max_count)
max[i]=1;
else
continue;
} // 1st_if
} //1st_for
printf("The most appearing characters are: ");
for (i=0; i<256; i++) {
if (max[i])
putchar(s[i]);
} //2nd_for
}

void leastOften(int *s) {
int i, j;
int min[256] = {0} ;
int min_count = 1000;
for (i=0; i<256; i++) {
if (s[i]) {
if (s[i] < min_count) {
for (j=0; j<256; j++)
min[j]=0;
min[i]=1;
min_count = s[i];
} // 2nd_if
else if (s[i] == min_count)
min[i]=1;
} // 1st_if
} //1st_for
printf("The least appearing characters are: ");
for (i=0; i<256; i++) {
if (min[i])
putchar(s[i]);
} //2nd_for
}

谢谢。

EDIT1:删除描述中的错误EDIT2:从 putchar(min[i]), putchar(max[i]) 更改为 putchar(s[i])

最佳答案

在您的mostOften 代码中,is 的索引,即字符itelf。因此,当您打印出最常出现的字符列表时,您应该打印字符 i 而不是 max[i]:

for (i = 0; i < 256; i++) {
if (max[i]) putchar(i);
}

另一种不需要将整个数组归零的方法是创建一个连续的字符列表。列表的长度是可变的,并保存在一个单独的变量 nmax 中。当您找到新的最大值时,只需将数组的长度设置为零。不要担心数组内容; max 仅保证具有高达 nmax 的敏感数据:

void mostOften(int *s)
{
int max[256]; // list of characters
int nmax = 0; // actual length of max array

int max_count = 0;
int i;

for (i = 0; i < 256; i++) {
if (s[i] && s[i] >= max_count) {
if (s[i] > max_count) nmax = 0;

max[nmax++] = i;
max_count = s[i];
}
}

for (i = 0; i < nmax; i++) printf("'%c'\n", max[i]);
}

关于c - 显示最少/最常出现的字符的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33738043/

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