How to calculate % change from X to Y in C++

1 Answer

0 votes
#include <iostream>
#include <cmath>
#include <iomanip>

double percentChange(double x, double y) {
    return ((y - x) / std::fabs(x)) * 100.0;
}

std::string describeChange(double x, double y) {
    double pct = percentChange(x, y);
    std::ostringstream out;

    out << std::fixed << std::setprecision(2);

    if (pct > 0) {
        out << "From " << std::setprecision(1) << x
            << " to " << y
            << std::setprecision(2)
            << " is a " << pct << "% increase (+" << pct << "%)";
    } else if (pct < 0) {
        out << "From " << std::setprecision(1) << x
            << " to " << y
            << std::setprecision(2)
            << " is a " << std::fabs(pct) << "% decrease (" << pct << "%)";
    } else {
        out << "From " << std::setprecision(1) << x
            << " to " << y
            << " is no change";
    }

    return out.str();
}

int main() {
    std::cout << describeChange(-80.0, 120.0) << "\n";
    std::cout << describeChange(120.0, 30.0) << "\n";
}



/*
run:

From -80.0 to 120.0 is a 250.00% increase (+250.00%)
From 120.0 to 30.0 is a 75.00% decrease (-75.00%)

*/

 



answered May 29 by avibootz
edited May 29 by avibootz
...