2

So I'm trying to learn more about C++ and I'm practicing by making a calculator class for the quadratic equation. This is the code for it down below.

#include "QuadraticEq.h"
 
string QuadraticEq::CalculateQuadEq(double a, double b, double c)
{
    double sqrtVar = sqrt(pow(b, 2) - (4 * a * c));
    double eqPlus = (-b + sqrtVar)/(2 * a);
    double eqMinus = (-b - sqrtVar) / (2 * a);
    return "Your answers are " + to_string(eqPlus) + " and " + to_string(eqMinus);
}

I'm trying to make it so that the double variables eqPlus and eqMinus have only two decimal points. I've seen people say to use setprecision() but I've only seen people use that function in cout statements and there are none in the class because I'm not printing a string out I'm returning one. So what would I do here? I remember way before learning about some setiosflags() method, is there anything I can do with that?

Jun Elbert
  • 21
  • 1
  • 7
    Floating point values do not have a set precision. You can set the precision when printing it, but that is changing the output format, not the actual value being printed. – Retired Ninja Sep 17 '22 at 04:44
  • You can do hacky things like multiplying by 100, rounding then dividing back by 100 but you won't necessarily get the right answer. If you want exactly 2 decimal places use fixed rather than floating point maths – Alan Birtles Sep 17 '22 at 05:46
  • 1
    Side note: you may also find this interesting/useful: [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Jesper Juhl Sep 17 '22 at 07:35

1 Answers1

1

You can use stringstream instead of the usual std::cout with setprecision().

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>

std::string adjustDP(double value, int decimalPlaces) {
    // change the number of decimal places in a number
    std::stringstream result;
    result << std::setprecision(decimalPlaces) << std::fixed << value;
    return result.str();
}
int main() {
    std::cout << adjustDP(2.25, 1) << std::endl; //2.2
    std::cout << adjustDP(0.75, 1) << std::endl; //0.8
    std::cout << adjustDP(2.25213, 2) << std::endl; //2.25
    std::cout << adjustDP(2.25, 0) << std::endl; //2
}

However, as seen from the output, this approach introduces some rounding off errors when value cannot be represented exactly as a floating point binary number.

Bunny
  • 1,180
  • 8
  • 22
  • why using stringstream when you only need to print to stdout? This adds so many extra layers so it's far more expensive – phuclv Sep 17 '22 at 07:54
  • OP might use the return value of the function for something else. In my case, I chose to output the return value to console just to show that the function works. – Bunny Sep 17 '22 at 09:56