我正在做比赛编码,在网站上,即黑客,我的程序给出了“错误控制到达非空函数的结尾 [-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/