给定一个二进制数组 nums,返回数组中连续的最大1的数量。

huangapple go评论59阅读模式
英文:

Given a binary array nums, return the maximum number of consecutive 1's in the array

问题

在Code blocks中可以工作,但在LeetCode上不行。有任何想法为什么。

英文:

I do not know why my code gives me this error -> solution.c: In function ‘findMaxConsecutiveOnes’
Line 32: Char 1: error: control reaches end of non-void function [-Werror=return-type] [solution.c]
}
^
cc1: some warnings being treated as errors.

int findMaxConsecutiveOnes(int* nums, int numsSize){
 
    int counter = 0;
    int max = 0;
    
    for(int i =0; i < numsSize; i++){
        if(nums[i] == 1){
            counter++;
        }
       else{
            counter = 0;
        }
        if(counter > max){
            max = counter;
        }
    }
    printf("%d", max);
}

This works in Code blocks but not leet code. Any idea why.

答案1

得分: 2

你的函数承诺返回一个 int,但从未返回任何类型的值。这就是为什么你收到这个警告/错误的原因。你可能是想在函数末尾返回 counter

英文:

Your function promises to return an int but never returns a value of any type. This is why you are getting this warning/error. Presumably you meant to return counter at the end of your function.

答案2

得分: 0

你的函数返回类型是 int 而不是 void,所以你必须返回一些整数值,这就是为什么你得到错误的原因。你的代码应该是:

int findMaxConsecutiveOnes(int* nums, int numsSize) {
    int counter = 0;
    int max = 0;

    for (int i = 0; i < numsSize; i++) {
        if (nums[i] == 1) {
            counter++;
        } else {
            counter = 0;
        }
        if (counter > max) {
            max = counter;
        }
    }
    printf("%d", max); // 你可以选择显示,如果你想显示
    // 将返回类型更改为 void,并且不要添加下一个返回语句,如果你想要这样做
    return max;
}
我认为这应该解决你的错误。

<details>
<summary>英文:</summary>

Your function return type is **int** not **void** so you have to return some int value that&#39;s why you are getting the error. Your code should be:

 

     int findMaxConsecutiveOnes(int* nums, int numsSize){
     
        int counter = 0;
        int max = 0;
        
        for(int i =0; i &lt; numsSize; i++){
            if(nums[i] == 1){
                counter++;
            }
           else{
                counter = 0;
            }
            if(counter &gt; max){
                max = counter;
            }
        }
        printf(&quot;%d&quot;, max); // it&#39;s upto you to show, if you want to show 
        //change return type to void and don&#39;t add next return statement
        return max;
    
    }

I think this should resolve your error

</details>



huangapple
  • 本文由 发表于 2023年5月15日 01:26:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76248817.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定