程序编译失败

时间:2013-12-31 19:26:06

标签: c++

这是我的代码。我正在使用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;
}

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

2 个答案:

答案 0 :(得分:9)

正如预测的那样,由于您使用了std::sqrt,错误是sqrtusing namespace std;之间发生符号冲突的结果。

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

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

正确的解决方案是不使用 using namespace std;。另见:Why is "using namespace std" considered bad practice?

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

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

避免在这些前面输入std::

说实话,编译器不应该包括math.h,正如其他人所指出的那样,使用10年以上的编译器是愚蠢的。使用现代编译器。

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

答案 1 :(得分:0)

相关问题