How to use whole numbers in a formula, and the result be a float with accurate two decimal digits?

Viewed 49

so my goal here is to write program that solves quadratic equations. But the values corresponding to a, h, and k must be whole numbers While the value of x must be a double precision real number with two decimal digit.

My problem occurs when I run the ints through the formula it just return me whole numbers. I know that if i change the ints from ints into doubles the program runs correctly but my professor wants them to be Whole numbers .

#include <iostream>             
#include <cmath>
#include <typeinfo>
#include <iomanip>
#include <string>
using namespace std;
int  main( )
{
int a = 3,h = 4,k = 5 ;
double x1;

x1 = -h + sqrt(k/a);
x1 = round(x1*100.00)/100.00;

cout << "The solutions for the equation are: " << endl << "                            " << "x1: " <<setprecision(2) << fixed << x1;

}
            
1 Answers

You can use static_cast<double>:

#include <iostream>
#include <cmath>
#include <typeinfo>
#include <iomanip>
#include <string>
using namespace std;
int main() {
    string name;
    int a, h, k;
    double x1, x2;

    cout << "Please enter your name: ";
    cin >> name;

    cout << endl << "Please enter the known terms for the quadratic equation" << endl;
    cout << "a: ";
    cin >> a;
    cout << endl << "h: ";
    cin >> h;
    cout << endl << "k: "; 
    cin >> k;

    cout << endl << "Thanks, " << name << "";
    // Calculates x1 using the formula -h + square root(k/a)
    x1 = -h + sqrt(static_cast<double>(k)/a);
    // Rounds x1 to the second decimal digit and reassigns it to x1
    x1 = round(x1*100.00)/100.00;
    // Ditto for x2
    x2 = -h - sqrt(static_cast<double>(k)/a);
    x2 = round(x2*100.00)/100;
    cout << "The solutions for the equation are: " << endl << "                            " << "x1: " << setprecision(2) << fixed << x1;
    cout << endl << "                            " << "x2: " << setprecision(2) << fixed << x2;
} 

Because both of the operands were integers, it used integer division, which rounds afterwards. By casting one operand to double, we use regular division.

Other comments: I fixed the formula for x2, which used + instead of -. Also, I did a bit of indentation and other formatting. This was a case of ridiculous over-commenting; I know what most of those lines do, they aren't that complicated. I removed most of the unnecessary comments.

Related