gpt4 book ai didi

c++三角函数返回意外值

转载 作者:搜寻专家 更新时间:2023-10-31 02:05:32 25 4
gpt4 key购买 nike

我被指派编写一个程序,该程序将以度为单位的 int 或 float 作为输入并返回该值的 sincos,小数点后 6 位.但是当输入为 90 和 180 时,我得到奇怪的负零,而不是“正”零。

代码:

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

const double PI = 3.14159265;

int main() {
float x;
cin >> x;
x = x * PI / 180;
cout << fixed;
cout << setprecision(6) << sin(x);
cout << ' ' << setprecision(6) << cos(x) << endl;

}

不需要的输入和输出:

In:90 Out:1.000000 -0.000000
In:180 Out:-0.000000 -1.000000

我尝试通过在输入为 90 时将 cos 函数的结果乘以 -1 来解决此问题,但它仍然输出 -0.000000。

解决方法:正如@harold 和@user2618142 指出的那样,计算结果为负,因此近似值返回负 0。

最佳答案

让我们取接近 90 度的余弦,接近 pi/2 弧度。在该区域,余弦的行为类似于 cos(x) ≈ pi/2 - x。

所以期望值是实际圆周率的一半(以其完整的无限数字精度)与我们作为参数给出的“半圆周率”之间的差值。我们作为参数给它的半圆周率实际上不可能是真正的半圆周率,因为它会有无限的数字。所以已经很清楚,无论结果是什么,它绝对不完全为零。

此处计算的实际值是按步骤计算的:

PI = 3.14159265 = 3.141592650000000208621031561051495373249053955078125
90 * PI = 282.74333849999999301871866919100284576416015625
90 * PI / 180 = 1.570796324999999882265910855494439601898193359375
(float)(90 * PI / 180) = 1.57079637050628662109375

最后,作为WolframAlpha会告诉我们,pi/2 和那个数字之间的差大约是 -4.371139000186243... × 10^-8,所以是负数。

关于c++三角函数返回意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51820357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com