Given two numbers, write a C program to calculate percentage difference between those two numbers.
Page Contents
If user entered numbers are stored in variables a and b. Then the formula to calculate the percentage difference between a and b is:
result = ( |a-b| / ((a+b) / 2.0) ) * 100;
OR
result = ( abs(a-b) / ((a+b) / 2.0) ) * 100;
Note: abs() is a builtin method present in stdlib.h header file, which returns the absolute value.
Related Read:
Basic Arithmetic Operations In C
Check this video tutorial to know more about absolute value:
C Program To Find Absolute Value of a Number
The percentage difference between two numbers is calculated by dividing the absolute value of the difference between two numbers by the average of those two numbers. And then multiplying the result by 100.
User Input:
Enter 2 numbers
100
200
Output:
Percentage difference is 66.666664
Video Tutorial: C Program To Calculate Percentage Difference Between 2 Numbers
#include<stdio.h> #include<stdlib.h> int main() { float a, b, result; printf("Enter 2 numbers\n"); scanf("%f%f", &a, &b); result = ( abs(a-b) / ( (a+b)/2.0 ) ) * 100; printf("Percentage difference is %f\n", result); return 0; }
Output 1:
Enter 2 numbers
50
60
Percentage difference is 18.181818
Output 2:
Enter 2 numbers
60
50
Percentage difference is 18.181818
Output 3:
Enter 2 numbers
75
75
Percentage difference is 0.000000
Output 4:
Enter 2 numbers
75
100
Percentage difference is 28.571428
Output 5:
Enter 2 numbers
150
200
Percentage difference is 28.571428
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert