程序编译失败
Program failed to compile
这是我的代码。我使用的是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::sqrt
和sqrt
之间的符号冲突的结果。
标头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.h
和making is_prime
bool
。
重载的'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还没有标准化的时候的一个标题。所以…是的。。。把书换一下。。。
- luaL_dofile在已知良好的字节码上失败,可以使用未编译的版本
- 包含模板文件的递归会导致编译失败
- 提升 1.64 单元测试编译失败
- 如何让谷歌测试正常运行。测试总是失败。(它不会编译)
- 运行时检查失败 #0 用于运行时重新编译
- C++模板的模板编译失败
- 使用已删除的函数进行编译失败,并显示 uclibc
- MinGW-w64 编译失败,nullptr_t
- 使用提升线程时编译失败
- 编译花絮 g++, clang++, 使用 libboost -- g++8 编译失败时 g++7 成功;
- 编译成功,使用 clang 5.0.1/6.0.0 ,在 5.0.2/6.0.1 时失败
- CMake + Qt,moc 编译失败,无法实现 QMetaObject 方法(编译器找不到基本 ui 对象的标头?
- 带有引用的std::tuple在clang中编译失败,但在gcc中编译失败
- bitbake-grpc交叉编译/配置失败,错误为c-ares::care引用文件/usr/lib/libcares.s
- 解决由于在哈希函数中使用了不完整的类型而导致的编译失败
- 将XCode升级到verison 11.1后,C++编译失败
- 继承的构造函数,在 clang++3.9 中编译,在 g++ 7 中失败
- C++:此代码可以编译,但引发运行时检查失败 #2 - 围绕变量周围的堆栈'num'已损坏。发生
- 添加类型名会导致程序编译失败
- 将 qi::lexeme 添加到灵气中的规则时编译失败