CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Mar 2002
    Location
    AhuhA
    Posts
    204

    Smile 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.

  2. #2
    Join Date
    Aug 2002
    Location
    Madrid
    Posts
    4,588
    [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.

  3. #3
    Join Date
    Mar 2002
    Location
    AhuhA
    Posts
    204

    Cool Thanks anyway!!!

    I still wonder why template can not be any help in this case. So could anyone give me the reason.





    Best regards,

  4. #4
    Join Date
    Sep 2002
    Posts
    1,747
    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

  5. #5
    Join Date
    Mar 2002
    Location
    AhuhA
    Posts
    204

    Thumbs up 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
  •  





Click Here to Expand Forum to Full Width

Featured