Click to See Complete Forum and Search --> : Simple Template question, help please!!!


Wfranc
February 10th, 2003, 10:34 AM
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' ;)]

Yves M
February 10th, 2003, 11:18 AM
[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.

Wfranc
February 11th, 2003, 01:12 AM
I still wonder why template can not be any help in this case. So could anyone give me the reason.





Best regards,

galathaea
February 11th, 2003, 01:52 AM
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!

Wfranc
February 12th, 2003, 12:48 AM
Perfectly !!!:D

Once again thank you, S.Galathaea !!!:)


Regards,