C++ sqrt 函数返回截断的(错误的)输出

C++ sqrt function returning truncated (wrong) output

我对math.h

的函数sqrt有疑问

我正在调试一些代码,我发现我的函数不能正常工作,因为 2/3 的平方根总是返回零。

我试图通过在单独的文件中写下一些平方根计算来隔离问题,但函数没有返回正确的值。

我是不是漏掉了什么?

#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;

}

这是我收到的输出:

0
2.82843
2

正确的输出应该是:

0.81650
2.82843
2.12132

提前致谢。

1,2,4,8,9是整数常量,整数的运算结果永远是整数

因此,你应该使用 double 常量,所以你应该尝试:

cout << sqrt(2.0/3.0) << endl;
cout << sqrt(16.0/2.0) << endl;
cout << sqrt(9.0/2.0) << endl;