-2

I was struggling to understand why the following snippet calculating information wrong:

result = sqrt(5/8 + sqrt(5)/8);
printf("Result is %1.15Lf\n", result);

I tried to separate and calculate one part first and than another, and still having same issue.

It's giving me:

Result is 0.528685631720282

While I checked the result with WolframAlpha and it is around 0.9510565.

NAND
  • 663
  • 8
  • 22
Venny
  • 1
  • 2

1 Answers1

0

Run this code you will get the right result:

long double result = sqrt(5.0/8.0 + sqrt(5.0)/8.0);
printf("Result is %1.15Lf\n", result);

All the digits in your function were integers and I am not aware of the data type of result in your program but it should also be the same type as you expect the result to be.

As you mentioned you just started learning C. Please read about data types importance in division, multiplication etc.

Denis
  • 1,219
  • 1
  • 10
  • 15
  • 1
    `sqrt` returns `double`, there is no point then converting that result to .`long double`. If you want to do square root in long double precision, use `sqrtl`. And use long double literals too. – M.M Mar 22 '16 at 03:51
  • In the printf it was already defined as long double output. Considering that this is how he user wants it to be I didn't changed it. But also user didn't defined the data type of result in question so I had to make it clear too that it can not be an int – Denis Mar 22 '16 at 03:55