How to calculate % change from X to Y in C

1 Answer

0 votes
#include <stdio.h>
#include <math.h>

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

void describeChange(double x, double y) {
    double pct = percentChange(x, y);

    if (pct > 0) {
        printf("From %.1f to %.1f is a %.2f%% increase (+%.2f%%) \n", x, y, pct, pct);
    } else if (pct < 0) {
        printf("From %.1f to %.1f is a %.2f%% decrease (%.2f%%) \n",
               x, y, fabs(pct), pct);
    } else {
        printf("From %.1f to %.1f is no change\n", x, y);
    }
}

int main() {
    describeChange(-80.0, 120.0);
    describeChange(120.0, 30.0);

    return 0;
}



/*
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
...