log10

R

RB Smissaert

Just starting with C++ in MS VC6++.

Why does this:

return (log10(70));

produce 1 and not 1.845098 ?

I can see it is giving me the rounded integer number, but why?
The return type of the function is a double.
Thanks for any advice.

RBS
 
J

Jerry Coffin

@fe2.news.blueyonder.co.uk>,
(e-mail address removed) says...
Just starting with C++ in MS VC6++.

Why does this:

return (log10(70));

produce 1 and not 1.845098 ?

It's virtually impossible for us to guess without seeing
your actual code. As written, it shouldn't compile --
log10 is overloaded for float, double and long double
arguments. You're passing an int, so all of these are
equally acceptable possibilities, creating an ambiguity.
To get this to compile as C++, you could use something
like 'return log10(70.0);' instead. Since you're passing
a double, the overload taking a double becomes preferred
and the ambiguity is removed.

If it's compiling as-is, you're probably compiling the
code as C. In this case, my first guess at the problem is
that you're not including <math.h>, so the proper return
type for the function isn't known (to the compiler). In
that case, it assumes the function returns an int. That
means the compiler will take whatever bit pattern it
returns and assume it's an int. Since you defined your
function to return a double, it's then converting that
bit pattern to a double. The fact that it's close to the
value you expected is mostly accidental.

Both of these seem to give correct answers:

// C++
#include <math.h>
#include <iostream>

int main() {
std::cout << log10(70.0);
return 0;
}

// C (won't compile as C++)
#include <math.h>
#include <stdio.h>

int main() {
printf("%f\n", log10(70));
return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top