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

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

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.

  1. int findMaxConsecutiveOnes(int* nums, int numsSize){
  2. int counter = 0;
  3. int max = 0;
  4. for(int i =0; i < numsSize; i++){
  5. if(nums[i] == 1){
  6. counter++;
  7. }
  8. else{
  9. counter = 0;
  10. }
  11. if(counter > max){
  12. max = counter;
  13. }
  14. }
  15. printf("%d", max);
  16. }

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,所以你必须返回一些整数值,这就是为什么你得到错误的原因。你的代码应该是:

  1. int findMaxConsecutiveOnes(int* nums, int numsSize) {
  2. int counter = 0;
  3. int max = 0;
  4. for (int i = 0; i < numsSize; i++) {
  5. if (nums[i] == 1) {
  6. counter++;
  7. } else {
  8. counter = 0;
  9. }
  10. if (counter > max) {
  11. max = counter;
  12. }
  13. }
  14. printf("%d", max); // 你可以选择显示,如果你想显示
  15. // 将返回类型更改为 void,并且不要添加下一个返回语句,如果你想要这样做
  16. return max;
  17. }
  18. 我认为这应该解决你的错误。
  19. <details>
  20. <summary>英文:</summary>
  21. 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:
  22. int findMaxConsecutiveOnes(int* nums, int numsSize){
  23. int counter = 0;
  24. int max = 0;
  25. for(int i =0; i &lt; numsSize; i++){
  26. if(nums[i] == 1){
  27. counter++;
  28. }
  29. else{
  30. counter = 0;
  31. }
  32. if(counter &gt; max){
  33. max = counter;
  34. }
  35. }
  36. printf(&quot;%d&quot;, max); // it&#39;s upto you to show, if you want to show
  37. //change return type to void and don&#39;t add next return statement
  38. return max;
  39. }
  40. I think this should resolve your error
  41. </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:

确定