3

I am writing an average function that takes the average of an array, and returns the answer to 2 decimal places. The only way I found online to do this, however, is by using printf() or cout().

But I do not want it to be printing out each time this function is called because it is used in other functions such as a variance equation and standard deviation equation that shouldn't be displaying the average function.

If anyone could tell me a way to do this, I would be eternally grateful. I think my question is broad enough that code isn't really needed, but here it is anyway just in case. It just continues for quite a few decimal points. Not sure if that's the exact value or a cut off point.

double avg(int a[],int n) // compute the average of n data storing in the array a
{
    double addsum = (double)sum(a,n)/(double)n;
    return addsum;
}
Arun A S
  • 5,531
  • 3
  • 25
  • 39
Tom Plutz
  • 77
  • 1
  • 6

4 Answers4

4

Since floating point values are always in binary, the best you can do is to return the closest binary number to the decimal that you really desire. But that process is relatively easy.

double round_two_places(double x)
{
    return floor(x * 100.0 + 0.5) / 100.0;
}
Mark Ransom
  • 271,357
  • 39
  • 345
  • 578
3

Use the ceil function from header file math.h in the following way to round off up to two decimal points:

double avg(int a[], int n) 
{
    double addsum = (double) sum(a, n) / (double) n;
    addsum = ceil(x * 100.0 - 0.5) / 100.0;
    return addsum;
}
Mathlight
  • 5,847
  • 15
  • 58
  • 103
2

You could shift the value truncate it and shift it back.

Example Code

double round(double value, unsigned n)
{
    double shift = std::pow(10, n);
    value *= shift;
    value = (int) value;
    value /= shift;
    return value;
}

int main()
{
    double value = 1.23456;
    std::cout << "before: " << value << ", after: " << round(value, 2) << "\n";
    return 0;
}

Caveat: This code may not be sufficient for all use cases (e.g., when round large numbers and/or rounding to many decimal places)

Example Output

before: 1.23456, after: 1.23
James Adkison
  • 8,891
  • 2
  • 25
  • 39
2

std::round gives you the closest integer to its argument. To simulate this rounding of the 3rd digit after the decimal point, use std::round(addsum*100.0)/100.0.

double avg(int a[],int n) // compute the average of n data storing in the array a
{
    double addsum = (double)sum(a,n)/(double)n;
    return std::round(addsum*100.0)/100.0;
}
Pradhan
  • 15,095
  • 3
  • 39
  • 56