今天,我试图回答this post (关于检查三角形是否可以构造),当我遇到一个奇怪的结果时。
经15.15 35.77 129.07
的测试,这段代码:
#include <iostream>
using namespace std;
const double e = 0.000001;
void f(double a, double b, double c)
{
if (abs(180 - (a+b+c)) > e) {cout << "test"; }
}
int main()
{
double a,b,c; cin >> a >> b >> c;
f(a,b,c);
}
版画 test
像往常一样,而这个:#include <iostream>
const double e = 0.000001;
void f(double a, double b, double c)
{
if (abs(180 - (a+b+c)) > e) {std::cout << "test"; }
}
int main()
{
double a,b,c; std::cin >> a >> b >> c;
f(a,b,c);
}
才不是。唯一的区别是 using namespace std;
行(当我将 using namespace std;
添加到第二段代码时,正如预期的那样,它运行正常)。我已经阅读了很多关于
using namespace std;
的帖子随着时间的推移:但似乎唯一的东西
using namespace std;
做的是偷工减料,以换取偶尔的类/变量/命名空间名称冲突(这是讨论是否使用它时最常提到的一点)。我确实找到了 1 个相关帖子:Why does g++ (4.6 and 4.7) promote the result of this division to a double? Can I stop it? ,但我没有在其他地方找到更多信息。
那么我在这里错过了什么?
-- 一些机器信息:
最佳答案
您确实存在名称冲突: int abs(int)
与 double std::abs(double)
.
与 using namespace std;
, abs(180 - (a+b+c))
找到两者和 std::abs
是更好的匹配。
无 using namespace std;
, abs(180 - (a+b+c))
只找到前者和转换为 int
是必要的,因此观察到的行为。
你真正想要的是:
#include <iostream>
const double e = 0.000001;
void f(double a, double b, double c)
{
if (std::abs(180 - (a+b+c)) > e) {std::cout << "test"; }
}
int main()
{
double a,b,c; std::cin >> a >> b >> c;
f(a,b,c);
}
关于c++ - 为什么在 C++ 中处理 double 时 "using namespace std;"会给出不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68133255/