-1

I have a doubt on the function sqrt of math.h

I was debugging some code, and I figured out that my function was not working properly, as the square root of 2/3 was always returning zero.

I tried to isolate the problem by just writing down some square root calculations in a separate file, and the function isn't returning the correct values.

Am I missing something?

#include <math.h>
#include <iostream>

using namespace std;
int main(){
        cout << sqrt(2/3) << endl;
        cout << sqrt(16/2) << endl;
        cout << sqrt(9/2) << endl;
        return 0;

}

This is the output I receive:

0
2.82843
2

When the correct output should be:

0.81650
2.82843
2.12132

Thank you in advance.

1 Answers1

3

1,2,4,8,9 are integers constants, and the arithmetic result of integers will always be an integer.

Therefore, you should work with double constants, so you should try:

cout << sqrt(2.0/3.0) << endl;
cout << sqrt(16.0/2.0) << endl;
cout << sqrt(9.0/2.0) << endl;
SHR
  • 7,940
  • 9
  • 38
  • 57