简体   繁体   English

为什么我的程序返回错误的值?

[英]Why is my program returning the wrong value?

I'm trying to write a program that takes a string as an input, and returns any characters in the string which occur more than once, along with how frequently they occur.我正在尝试编写一个程序,该程序将字符串作为输入,并返回字符串中出现不止一次的任何字符,以及它们出现的频率。 What I haven't been able to figure out is finding a way to get the program to return "No duplicates found" for strings with no repeating characters.我无法弄清楚的是找到一种方法让程序为没有重复字符的字符串返回“未找到重复项”。

# 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;
}

The program returns characters that occur more than once along with their frequency, but it always returns "No duplicates found" along with this.该程序返回出现不止一次的字符及其频率,但它始终返回“未找到重复项”。 How can i fix it so it only returns "No duplicates found" for strings with no repeating characters?我该如何修复它,以便它只为没有重复字符的字符串返回“未找到重复项”?

You need to use a flag/counter say dupe_chars to track if one or more duplicate characters were found.您需要使用标志/计数器说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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM