在C99中,'sum'函数的隐式声明无效

5

我一直在寻找解决办法,但没有找到任何有帮助的东西。 我遇到了以下错误:

Implicit declaration of function 'sum' is invalid in C99

Implicit declaration of function 'average' is invalid in C99

Conflicting types for 'average'

有人之前遇到过这种情况吗?我正在尝试在Xcode中编译它。

#import <Foundation/Foundation.h>


    int main(int argc, const char * argv[])
    {

       @autoreleasepool
       {
          int wholeNumbers[5] = {2,3,5,7,9};
          int theSum = sum (wholeNumbers, 5);
          printf ("The sum is: %i ", theSum);
          float fractionalNumbers[3] = {16.9, 7.86, 3.4};
          float theAverage = average (fractionalNumbers, 3);
          printf ("and the average is: %f \n", theAverage);

       }
        return 0;
    }

    int sum (int values[], int count)
    {
       int i;
       int total = 0;
       for ( i = 0; i < count; i++ ) {
          // add each value in the array to the total.
          total = total + values[i];
       }
       return total;
    }

    float average (float values[], int count )
    {
       int i;
       float total = 0.0;
       for ( i = 0; i < count; i++ ) {
          // add each value in the array to the total.
          total = total + values[i];
       }
       // calculate the average.
       float average = (total / count);
       return average;
    }

检查这个答案,对我来说非常有效! https://dev59.com/pFYO5IYBdhLWcg3wL-rY#46221365 - Heitor
2个回答

10

您需要为这两个函数添加声明,或将这两个函数的定义放在 main 函数之前。


不是。请查看 https://dev59.com/pFYO5IYBdhLWcg3wL-rY#46221365,解释和解决方案都在那里! - Heitor

7
问题在于编译器在看到你使用 sum 的代码时,并不知道任何带有该名称的符号。你可以进行前向声明来解决此问题。
int sum (int values[], int count);

将此代码放在main()之前。这样,当编译器看到第一次使用sum时,它知道它存在并且必须在其他地方实现。如果没有,则会出现行错误。

我修复了它,谢谢你指引我正确的方向。我还必须包括:int sum (int values[], int count); float average (float values[], int count ); 在 main() 上面。 - uplearned.com
1
我修复了它,谢谢Nick。我还不得不添加:float average(float values[], int count); - uplearned.com

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接