2

I have a problem with rounding. I need a 6 decimal precision and in "spoj" i get a good result, but the cout or printf round my outcome to 2 decimals. I tried using printf but still console rounds my outcome. How can i avoid this?

#include <iomanip>
#include <string>

void spoj(double** tab, double* vector, int columns, int rows)
{
    double** tab_t = new double* [columns];
    for (int i = 0; i < columns; i++)
    {
        tab_t[i] = new double[rows];
    }

    for (int i = 0; i < columns; i++)
    {
        for (int j = 0; j < rows; j++)
        {
            tab_t[i][j] = tab[j][i];
        }
    }
    //for (int i = 0; i < columns; i++)
    //{
    //  for (int j = 0; j < rows; j++)
    //  {
    //      std::cout << tab_t[i][j] << " ";
    //  }
    //  std::cout << "\n";
    //}

    double* outcome = new double[columns];
    for (int i = 0; i < columns; i++)
    {
        outcome[i] = 0;
        for (int j = 0; j < rows; j++)
        {
            outcome[i] += tab_t[i][j] * vector[j];
        }
    }

    for (int i = 0; i < columns; i++)
    {
        printf("%.6f", outcome[i]);
        std::cout << " ";
    }
}

Adam Gajek
  • 29
  • 1
  • Please post the expected output and the actual output. – R Sahu Nov 21 '19 at 22:32
  • 2782.81 instead of 2782.8083 and i also dont want to use std::setprecision because i prints "2782.808300" – Adam Gajek Nov 21 '19 at 22:37
  • I'm not sure about this at all (that's why I'm putting it as a comment) but is it because of `%.6f` thinking of it being 6 digits in total instead of 6 digits decimal? – Axiumin_ Nov 21 '19 at 22:39
  • 3
    You asked it for 6 digits and it gave you 6 digits. If you want 8 digits, you should ask for that. – Chris Dodd Nov 21 '19 at 22:40
  • i want my program to print 6 decimals avoiding the meaningless zeros - x.1201 insted of x.120100 – Adam Gajek Nov 21 '19 at 22:43
  • 2
    @AdamGajek, this is what a [mcve] would look like for your problem. https://ideone.com/6lVgX0. Anything else that you post is a hindrance in formulating a sensible answer. – R Sahu Nov 21 '19 at 22:43
  • 1
    "_meaningless zeros_" - Would those last digits have been meaningful if they contained anything but zeroes? If yes, then the zeroes are meaningful too. If you only want 4 decimals, `"%.4f"`. – Ted Lyngmo Nov 21 '19 at 22:47
  • let me make it more clear. 6 decimals are important for me and i want my program to cout whole number without rounding. Moreover I want him to cut the zeros at the end – Adam Gajek Nov 21 '19 at 22:53
  • 1
    I'm not sure I understand completely what you want but `%g` for printf and `std::defaultfloat` for IOstreams allows to output floating point values while removing trailing `0`. What I'm not sure is if their notion of precision is the one you want. – AProgrammer Nov 21 '19 at 23:18

0 Answers0