我刚刚编写了应该显示最多/最少(取决于开关选择)出现字符的代码。它必须使用标准输入,即来自键盘以及文本文件的输入。显示最常出现的所有字符对于该程序至关重要。例如在输入“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
代码中,i
是s
的索引,即字符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]);
}
我是一名优秀的程序员,十分优秀!