【问题标题】:Check for double characters - Functions检查双字符 - 函数
【发布时间】:2021-02-19 04:08:20
【问题描述】:

我创建了一些代码,可以检查输入文本中的双字符。如果我的所有代码都在我的 main 函数中,我就可以开始工作了,但是当我想创建一个额外的函数时会遇到一些麻烦。我得到的错误如下:“错误:控制可能到达非无效函数的结尾”,我已经确定系统无法识别我的 count_double_characters 函数的返回值。

你能帮我理解我做错了什么吗?

#include <stdio.h>
#include <string.h>

int count_double_characters(char *ch);

int main(void)

{
char input[400];
printf("Write the text you want to check: ");
fgets(input, sizeof(input), stdin);
count_double_characters(input);
}   


int count_double_characters(char *ch)
{
char n = strlen(ch);  
int count_double = 0;

for (int i = 0; i < n; i++)
{
    for (int j = i + 1; j < n; j++)
    {
        if (ch[i] == ch[j])
        {
            count_double++;
        }
    }

}

if (count_double > 0)
    {
        char s = printf("Its a double!\n");
        return s;
    }
    
else if (count_double == 0)
    {
        char d = printf("Looks good\n");
        return d;
    }
}

【问题讨论】:

  • 问题是:你有一个 if 块返回一个值,一个 else if 块也返回一个值,但你没有最终的 else 块返回一个值,在换句话说:您需要涵盖所有情况。
  • 谢谢!我得到了工作的代码:)
  • 在更高级别的代码中使用char input[400];char n = strlen(ch); 是狡猾的。推荐size_t n = strlen(ch);
  • 感谢您的回答。我可以看到这更有意义:) 谢谢!

标签: c function return-value


【解决方案1】:

考虑您的代码的这一部分:

if (count_double > 0)
    {
        char s = printf("Its a double!\n");
        return s;
    }
    
else if (count_double == 0)
    {
        char d = printf("Looks good\n");
        return d;
    }

  // if count_double is less than 0, the program goes here
  // but there is non return statement, meaning that the function
  // does not return any value.
  // That what's the error message is telling you
}

现在你会告诉我count_double 永远不能为 0,这是正确的,但显然编译器不够聪明,无法检测到这一点。

要更正,您可以简单地删除 if (count_double == 0) 或将其替换为 if (count_double &lt;= 0)

【讨论】:

  • 非常感谢!太愚蠢了,我没有想到这一点!我的代码现在可以工作了:)
猜你喜欢
  • 2013-03-14
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-11
  • 2012-03-27
相关资源
最近更新 更多