c - 现场程序错误但不在代码块上

标签 c arrays codeblocks

我正在做比赛编码,在网站上,即黑客,我的程序给出了“错误控制到达非空函数的结尾 [-Werror=return-type]”,但在代码块上它工作正常,这是我的代码。

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int count_max_freq(int *a,int n,int i)
{   static int max_freq=0,index;
    int t=a[i],f=0;
    for(int j=i;j<n;j++)
        if(a[i]==a[j])
            f++;
    if(max_freq<f)
    {   max_freq=f;
        index=i;
    }
    if(i<n)
        count_max_freq(a,n,i+1);
    else
        return a[index];
}
int main(){
    int n;
    scanf("%d",&n);
    int *types = malloc(sizeof(int) * n);
    for(int types_i = 0; types_i < n; types_i++){
       scanf("%d",&types[types_i]);
    }
    // your code goes here
    printf("%d",count_max_freq(types,n,0));
    return 0;
}

最佳答案

其中一个返回路径不返回任何东西(递归路径)因此出现警告。

它能正常工作纯属运气(不确定你所说的工作是什么:“它编译”并不意味着“它正常运行”,好吧它可以只是运气,但我不会打赌)

我的建议:替换它:

if(i<n)
    count_max_freq(a,n,i+1);  // should return the value!
else
    return a[index];

通过一个三元表达式,所以你只有一个 return 语句,没有警告,而且它在任何地方都有效:

return (i<n) ? count_max_freq(a,n,i+1) : a[index];

关于c - 现场程序错误但不在代码块上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42178875/

相关文章:

c++ - 将多参数函数传递给宏

ios - 如何让函数接受所有类型的数组

java - 将 if/else block 转换为三元运算符时的错误答案

c++ - Codeblocks 中的图形程序

sql - 在 postgres 中实现用户定义的 c 函数

c - gcc: "="标记之前的预期表达式

ruby - 根据字符串的一部分对 Ruby 数组进行排序

c - 适用于 Windows 7 64 位的 c 和 c++ 的 mingw 和代码块?

c++ - 无法使用代码块编译 C++ 类

c - GTK3 中的可滚动布局