2013-07-24 57 views
3

我很清楚函数原型,这个错误似乎是一个函数声明错误,这意味着我真的很困惑,为什么我看到这个警告,因此错误。函数的隐式声明x

这几乎就像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 

代码:

#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; 
} 
+3

对downvote的评论会很好。 – TheBlueCat

+0

为什么选择投票? – haccks

回答

10

点1
你在函数名称拼写错误largest

long largetsprime(long) 
     ^
      s is wrong here 

在声明中应当

long largestprime(long) 
     ^before t 

点2
您正在使用从math.hsqrt()库函数,你应该-lm为编译程序:

gcc -Wall -std=c99 -pedantic primefactors.c -lm 

点3
您正在返回int,而返回类型的功能是long

点4 一个更错误建议在printf()叫你忘记添加后缀long int

largestprime(600851475143) 

应该是:

largestprime(600851475143L) 
     //    ^added suffix L for long 

如果你不知道后缀L的然后阅读:What does the “L” mean at the end of an integer literal?

感谢@Eric Postpischil

点5:printf()main()功能正在打印long整数类型,而你已经使用%d格式说明打印:

printf("%d\n", largestprime(600851475143)); 
       ^
       | 
       returns long 

使用%ld代替。

点-6:

if在最大素功能i % 1 == 0 and i % i == 0 -condition各自总是为真(除了后者是未定义如果i是零),因为i % 1 = 0(每隔数为整除1)。

+0

感谢您的建议。在过去的几个小时里,我一直在重构这些代码来解决这个项目的问题;这可能不是我最好的代码。 – TheBlueCat

+1

@TheBlueCat没问题BlueCat!我只是想分享我所遇到的内容。没关系! –

+1

是的,我知道C中的文字。谢谢你。无论如何,我想这很有用。 – TheBlueCat

1

你有原型一个错字。它应该是largestprime而不是largetsprime

1

你必须在原型一个错字:

largetsprime != largestprime 
2

Typo。该声明说largeTSprime。将其更改为正确的largestprime,它将起作用。

ProTip#1:为了便于阅读,请使用camelCapsOnWordBoundariesunder_scores

ProTip#2:它几乎是从来没有编译器的错误。

+0

不错,99.99%的时间。 – TheBlueCat

+0

@TheBlueCat注意到'几乎'? – 2013-07-24 16:52:20

+0

我想更多地量化它; gcc非常稳定,尤其是在稳定的发行版上。 – TheBlueCat