[英]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.