Home > Blockchain >  Two different answers for same expression in C
Two different answers for same expression in C

Time:01-15

I have an expression which does the same calculation. When I try to do the whole calculation in a single expression and store it in variable "a", the expression calculates the answer as 0. When I divide the equations in two different parts and then calculate it, it gives the answer -0.332087. Obviously, -0.332087 is the correct answer. Can anybody explain why is this program misbehaving like this?

#include<stdio.h>

void main(){
    double a, b, c;
    int n=0, sumY=0, sumX=0, sumX2=0, sumY2=0, sumXY=0;
    n = 85;
    sumX = 4276;
    sumY = 15907;
    sumX2 = 288130;
    sumY2 = 3379721;
    sumXY = 775966;
    a = ((n*sumXY) - (sumX*sumY)) / ((n*sumX2)-(sumX*sumX));
    b = ((n*sumXY) - (sumX*sumY));
    c = ((n*sumX2) - (sumX*sumX));
    printf("%lf\n", a);
    printf("%lf\n", b/c);
}

Output:
0.000000
-0.332097

CodePudding user response:

In first equation i.e. a = ((nsumXY) - (sumXsumY)) / ((nsumX2)-(sumXsumX)) both numerator and denominator will give integer results and the value stored in a will also be integer as integer/integer is integer. In second and third expression as you are solving them individually both b and c will be stored in double and double/double will result in a double i.e. a decimal value. This problem can be solved by using type casting.

CodePudding user response:

In your program

a = ((n*sumXY) - (sumX*sumY)) / ((n*sumX2)-(sumX*sumX));

all the variables in the right hand side are of type int, so it will produce a result of type int. The true answer -0.332097 is not a int value, so it will be converted to a valid int value, namely 0. And this 0 is assigned to variable a.

But when you do

b = ((n*sumXY) - (sumX*sumY));
c = ((n*sumX2) - (sumX*sumX));
printf("%lf\n", b/c);

The variable b and c are of type double, so the expression b/c produce a double typed value and the true answer -0.332097 is a valid double value. Thus this part of your code give a right result.

CodePudding user response:

Change all your INTEGERS to DOUBLES. That should solve the problem

CodePudding user response:

The type of 1st expression is int whereas in 2nd expression it is double.

  •  Tags:  
  • Related