函数x的隐式声明

The*_*Cat 4 c algorithm prime-factoring

我很清楚函数原型,这个错误似乎是一个函数声明错误,这意味着我真的很困惑,为什么我看到这个警告,从而错误.

这几乎就像gcc完全忽略了我的函数原型.这是编译器错误吗?

为了简洁起见,我没有在单独的头文件中声明此函数,尽管它应该没有区别.

gcc输出:

$ gcc -Wall -std=c99 -pedantic primefactors.c
primefactors.c: In function ‘main’:
primefactors.c:8:5: warning: implicit declaration of function ‘largestprime’ [-Wimplicit-function-declaration]
primefactors.c: At top level:
primefactors.c:12:6: error: conflicting types for ‘largestprime’
primefactors.c:8:20: note: previous implicit declaration of ‘largestprime’ was here
Run Code Online (Sandbox Code Playgroud)

码:

#include <stdio.h>
#include <math.h>

long largetsprime(long);

int main()
{
    printf("%d\n", largestprime(600851475143));
    return 0;
}

long largestprime(long num)
{
    int highest;
    int mid = sqrt(num);
    for (int i = 2; i < mid; i++) {
        if (mid % i == 0) {
            if (i % 1 == 0 && i % i == 0)
                highest = i;
        }
    }
    return highest;
}
Run Code Online (Sandbox Code Playgroud)

Gri*_*han 11

Point-1
largest在函数名称中拼写错误

long largetsprime(long)
           ^
           s is wrong here 
Run Code Online (Sandbox Code Playgroud)

在声明它应该是

long largestprime(long)
          ^ before t
Run Code Online (Sandbox Code Playgroud)

Point-2
您正在使用sqrt()库函数math.h,您应该使用-lmas 编译您的程序:

gcc -Wall -std=c99 -pedantic primefactors.c -lm
Run Code Online (Sandbox Code Playgroud)

Point-3
您正在返回,int而您的函数的返回类型是long.

Point-4还有 一个错误printf()你打电话的建议忘记添加后缀long int.

largestprime(600851475143)
Run Code Online (Sandbox Code Playgroud)

应该:

largestprime(600851475143L)
      //                 ^ added  suffix  L for long 
Run Code Online (Sandbox Code Playgroud)

如果您不知道后缀,请L阅读:"L"在整数文字的末尾是什么意思?

感谢@ Eric Postpischil:

point-5: printf() in main()function是打印long类型整数,而你使用了%d格式说明符来打印它:

printf("%d\n", largestprime(600851475143));
                 ^
                 | 
                 returns long
Run Code Online (Sandbox Code Playgroud)

使用%ld来代替.

点6:

if最大素数函数 i % 1 == 0 and i % i == 0中的条件总是为真(除非后者i在零时未定义)因为i % 1= 0(每个数字都可被整除1).

  • 常量上的`L`后缀是不必要的.常量将是一个足以表示值的整数类型,它将转换为"long"以传递给函数.更值得关注的是格式说明符是'%d`,这是为'int`,但为它传递的值是'long`类型.另外`则i%1 == 0`和`我%I == 0`各自总是为真(除了后者是未定义如果`i`是零). (4认同)