[英]Why is my program returning the wrong value?
我正在尝试编写一个程序,该程序将字符串作为输入,并返回字符串中出现不止一次的任何字符,以及它们出现的频率。 我无法弄清楚的是找到一种方法让程序为没有重复字符的字符串返回“未找到重复项”。
# include <stdio.h>
# include <stdlib.h>
#include <ctype.h>
# define NO_OF_CHARS 256
char fillCharCounts (unsigned char *str, int *count) {
int i;
for (i = 0; * (str + i); i++)
count[* (str + i)]++;
return 0;
}
void printDups (unsigned char *str) {
int *count = (int *) calloc (NO_OF_CHARS, sizeof (int));
fillCharCounts (str, count);
int i;
for (i = 0; i < NO_OF_CHARS; i++)
if (count[i] > 1)
printf ("\nDuplicate letter: %c, Occurrences: %d", i, count[i]);
/* area of concern */
if (count[i] < 1)
printf ("\nNo duplicates found\n");
exit (0);
printf ("\n");
free (count);
}
int main() {
unsigned char str[15] = "";
printf ("Enter a word>");
scanf ("%s", str);
printDups (str);
getchar();
return 0;
}
该程序返回出现不止一次的字符及其频率,但它始终返回“未找到重复项”。 我该如何修复它,以便它只为没有重复字符的字符串返回“未找到重复项”?
您需要使用标志/计数器说dupe_chars
来跟踪是否发现一个或多个重复字符。
int dupe_chars = 0; // an integer flag/counter
for (int i = 0; i < NO_OF_CHARS; i++)
if (count[i] > 1) {
printf ("\nLetter: %c, Occurrences: %d", i, count[i]);
++dupe_chars; //counting duplicate letters
}
/* area of concern */
if (0 != dupe_chars)
printf ("\nDuplicates of %d chars were found\n", dupe_chars);
else
printf ("\nNo duplicates were found\n");
//exit (0); // not necessary
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.