程序编译失败

Program failed to compile

本文关键字:失败 编译 程序      更新时间:2023-10-16

这是我的代码。我使用的是Dev-C++4.9.8.0,我不明白为什么它不能编译。

#include <iostream>
#include <cmath>
#include <stdlib.h>
using namespace std;
int main() {
int  n;    // Number to test for prime-ness
int  i;    // Loop counter
int  is_prime = true; // Boolean flag...
// Assume true for now.
// Get a number form the keyboard.
cout << "Enter a number and press ENTER: ";
cin >> n;
// Test for prime by checking for divisibility 
// by all whole numbers from 2 to sqrt(n).
i = 2;
while (i <= sqrt(n)) {  // While i is <= sqrt(n),
if (n % i == 0)         // If i divides n, 
is_prime = false;   //    n is not prime.
i++;
}
// Print results
if (is_prime)
cout << "Number is prime." << endl;
else
cout << "Number is not prime." << endl;
system("PAUSE");   
return 0;
}

我收到各种关于过载的错误消息。有人能帮我弄清楚为什么它没有正确编译吗。

正如预测的那样,该错误是由于使用了using namespace std;而导致std::sqrtsqrt之间的符号冲突的结果。

标头cmath有一个名为std::sqrt的函数,而符号名称sqrt正因为您的using namespace std;而导入到您的命名空间中。尽管没有包含math.h,但由于某种原因,编译器也在导入该标头,而math.h定义了一个sqrt函数。

编译器抱怨它不知道该使用哪个sqrt

正确的解决方案是不要使用using namespace std;。另请参阅:为什么;使用命名空间std";被认为是不好的做法?。

在您的特定情况下,您可以用以下内容替换using namespace std;

using std::cout;
using std::cin;
using std::endl;

以避免总是在这些前面键入CCD_ 14。

老实说,编译器不应该包含math.h,正如其他人所指出的,使用一个已有10多年历史的编译器是愚蠢的。使用现代编译器。

编辑:此外,请不要再连续发布六条评论来传达多行错误消息。只需编辑您的原始帖子。

这在gcc中编译良好。

尽管有一些东西你可以改进,比如

不包括#include <stdlib.h>包括stdlib而不是stdlib.hmaking is_primebool

重载的'sqrt(int&)'的第22行调用的不明确

尝试sqrt<int>(n)sqrt((int) n)

@Andrey给出了答案:使用::sqrt(n)std::sqrt(n),或者包含math.h而不是cmath。正如他所建议的那样,最好还是不要使用using namespace std;

我的建议是:改用更主流的编译器,如gcc、clang或Visual Studio。它们更符合标准。

我正在使用的书使用Dev-C++

我不想刻薄,而是换一本第二本书。我不会相信一本让你把stdlib.h包括在内的书。这是C还没有标准化的时候的一个标题。所以…是的。。。把书换一下。。。