Today, I was trying to answer this post (regarding checking whether a triangle can be constructed), when I encountered a weird result.
With the test of 15.15 35.77 129.07
, this piece of code:
#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);
}
prints test
as normal, while this:
#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);
}
does not. The only difference is the using namespace std;
line (and when I added using namespace std;
to the second piece of code, as expected, it ran normally).
I've read a lot of post regarding using namespace std;
over time:
but it seems that the only things using namespace std;
do is cut some corners, in exchange of occasional conflicts of name of classes/variables/namespaces (the point that is brought up most when debating about whether to use it).
I did find 1 relevant post : Why does g++ (4.6 and 4.7) promote the result of this division to a double? Can I stop it? , but I didn't find anymore info elsewhere.
So what I'm I missing here?
-- Some machine info:
You do have a name conflict: int abs(int)
versus double std::abs(double)
.
With using namespace std;
, abs(180 - (a+b+c))
finds both and std::abs
is a better match.
Without using namespace std;
, abs(180 - (a+b+c))
only finds the former and a conversion to int
is necessary, hence the observed behaviour.
What you really want is:
#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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With