|
-
February 10th, 2003, 11:34 AM
#1
Hi
I wrote a function like this to get the largest value among the threes, but the returned value when 'cout'ed in the main function is the same-->12.4242. Could anyone here tell me why ?
template <typename T>
T max(T x,T y,T z){
T holdmax=x;
if(y>=holdmax)
holdmax=y;
if(z>=holdmax)
holdmax=z;
return holdmax;
}
int main(){
cout<<max(12.42422,12.42421,12.42420)<<endl;
return 0;
}
Thanks in advance
Regards,
[Yves: try to find a better title for your post than 'Hi' ]
Last edited by Yves M; February 10th, 2003 at 12:11 PM.
-
February 10th, 2003, 12:18 PM
#2
[Ups, sorry, I wanted to merge your cross-posted thread from VC++ with this one and accidentally deleted all of the replies ]
The answer is that the precision for cout for floating point numbers is too small. so try using setprecision(10) for example.
Get this small utility to do basic syntax highlighting in vBulletin forums (like Codeguru) easily.
Supports C++ and VB out of the box, but can be configured for other languages.
-
February 11th, 2003, 02:12 AM
#3
Thanks anyway!!!
I still wonder why template can not be any help in this case. So could anyone give me the reason.
Best regards,
-
February 11th, 2003, 02:52 AM
#4
Your template is neither helpful nor "hurtful" here. It is most likely returning the correct value here (even though, if I am not mistaken, the decimal literal is only a float, not a double?). The function is probably doing exactly what you want it to.
What is happening is that your command to display the number to the screen won't show you all of the digits until you set the output precision properly. Until you change this precision, the ostream will do some rounding for display which will make it look like you are not getting the right values.
Hope that makes it a little clearer!
*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/
"It's hard to believe in something you don't understand." -- the sidhi X-files episode
galathaea: prankster, fablist, magician, liar
-
February 12th, 2003, 01:48 AM
#5
Thanks
Perfectly !!!
Once again thank you, S.Galathaea !!!
Regards,
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|