• Advertisement
Sign in to follow this  

math function question

This topic is 3671 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I would like to know why this won't compile...when I enter the numbers into the math functions i get error messages saying something about overloading.. This one doesn't work...
//This doesn't work!??
#include <iostream>
#include <conio.h>
#include <cmath>

int main()
{
	std::cout << sqrt(10) << std::endl;

   getch();
   return 0;
} 




This one works...
//this works!
#include <iostream>
#include <conio.h>
#include <cmath>

int main()
{
	double sqrtNumber = 10;
	std::cout << sqrt(sqrtNumber) << std::endl;

   getch();
   return 0;
}




I don't understand why, they are both the exact same thing besides the one uses a variable assigned to the value of 10 instead of just using the number 10 right? please clarify

Share this post


Link to post
Share on other sites
Advertisement
The sqrt() function takes a double, not an int. By storing 10 in the variable of type double, it passes a double into the sqrt() function, but when you pass in 10 explicitly, it won't work because it doesn't take ints. Try typecasting 10, sqrt((double)10).

Share this post


Link to post
Share on other sites
what's the compiler error? It's perhaps assuming that 10 is an int, and not a double which sqrt accepts. Try replacing 10 with 10.0

-me

Share this post


Link to post
Share on other sites
Oh, I wasn't aware it only takes doubles and I have to typecast that.

Thank you :)!

Share this post


Link to post
Share on other sites
Quote:
Original post by zell901
Oh, I wasn't aware it only takes doubles and I have to typecast that.

Thank you :)!


No, you wouldn't want to typecast in the function call (although there's nothing really wrong with that), you'd want to just store them as a double, like you did. Also, there might be plenty of Math functions that take all kinds of parameters, so you could check in the API for your particular functions and see what they take.

Share this post


Link to post
Share on other sites
Yes that is a very common beginners error.
I made the same mistake when I first tried to use the sqrt function and as you can see the compiler error message isn't very helpful in this case!

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement