Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Setting precision? C++

  1. Oct 2, 2006 #1
    Hey.. I'm having trouble achieving this in C++...

    I'm trying to do an opperation but keeping only 2 decimals, and floor rounding.

    ((3.52 * 4.32)/3.26) + 2.34

    So I have 3.52 * 4.32 = 15.2064, but then I just round to 15.20

    then 15.20/3.26 = 4.662576687116, but then I just round to 4.66

    ... and so on...

    anyone know how to achive this in C++, I've thought of the floor command but how do I see the precision to only 2 decimals?
     
  2. jcsd
  3. Oct 2, 2006 #2

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    At each intermediate step, you'll need to:

    1) Multiply your floating-point numbers by 100.0 (to preserve two decimal places).

    2) Cast them to first to integers and then back to floating-point (which will truncate the rest of the decimal places). Alternatively, you can use the floor() function to truncate.

    3) Divide the resulting floating-point number by 100.0.

    - Warren
     
  4. Oct 2, 2006 #3

    0rthodontist

    User Avatar
    Science Advisor

    Why would you ever want to do that anyway? You'll just lose precision. It makes more sense to calculate with all the digits you have and only round at the end.
     
  5. Oct 7, 2006 #4
    Alright... I have the rounding working now, Thanks so much =).

    I'm printing the matrix giving a precision of 5 decimal places... I use

    int j, k;
    for (j = 0; j < n; j++) {
    for (k = 0; k < n + 1; k++) {
    printf (" %10.5f ", a[k][j]);
    }
    printf("\n");
    }
    printf("\n");

    however I want to vary the " %10.5f " to any precision I input... anyone know how to do this... I know there's a way with iomanip.. but I want to use printf because it does it nicer.
     
  6. Oct 7, 2006 #5

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    I would prefer to advise using the C++ i/o library. But, if you insist...

    The first argument to printf doesn't have to be a string constant...
     
  7. Apr 6, 2007 #6
    For more decimal places you could also try putting this in your code

    cout.precision(16);

    You need not use 16, but that(16 digits) is about the limit of you precision, if you are using type double.
     
    Last edited: Apr 6, 2007
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Setting precision? C++
Loading...