Find result of given mathematical expressions

C program to read the values of a, b, c, d and print the results for following expression.

i) x= a*b%c/d

ii) y = a*((b%c)/d)

iii) z=a*b+a*(c-d)


Solution:

In this program, read the values of a, b, c, d as an input and compute the result of above expression.

#include<stdio.h>
int main()
{
      int a,b,c,d;
      float x=0,y=0,z=0;
      // If we do not assign zero then in some cases compiler might be taken garbage value with result.
      printf("Enter Value for a = ");
      scanf("%d",&a);
      printf("Enter Value for b = ");
      scanf("%d",&b);
      printf("Enter Value for c = ");
      scanf("%d",&c);
      printf("Enter Value for d = ");
      scanf("%d",&d);
      x=a*b%c/d;         // Expression-1 for accurate result we can do type-casting here
      y=a*((b%c)/d);      // Expression-2
      z=a*b+a*(c-d);       // Expression-3
      printf("\nResult of Expression-1 = %.2f\n",x);
      printf("Result of Expression-2 = %.3f\n",y);
      printf("Result of Expression-3 = %.2f\n",z);
      return 0;
}


Output:

mathematical expressions

Note - Above output is obtained without type-casting the variables in the expression.

mathematical expressions

Above output is obtained after type-casting the variables in an expression. After type-casting the variables, expression is written as:

x = a*b%c/(float)d;

y = a*((b%c)/(float)d);