gpt4 book ai didi

c - 函数计算结果错误答案

转载 作者:行者123 更新时间:2023-11-30 20:18:43 24 4
gpt4 key购买 nike

我正在做练习,并且坚持使用我的代码。希望大家能帮我解决一下。

enter image description here

这是我的函数fen():

double fen(double x,double y, int n) { // You should complete this function
// Write your statements here
double sum=1,temp;
int j=2,k=1;
double a = (x*y*y) / 18;
sum=1-a;
for(int i=2;i<=n;i++)
{
for(;j<=i;j++)
{
a *= (x*y);
for(;k<=(i+j);k++)
a /= k;
}
temp = a/(k*k);
temp = (i%2 == 0) ? temp : -temp;
sum+=temp;
}

return sum; //This statement must be changed
}

我检查了很多次,但还是不知道为什么结果是错误的。我已经调试过,当i=3时,a实际上等于0.025,但它显示0.02499999999

最佳答案

我编写了一段小代码来简化事情,如下:

#include <iostream>
using namespace std;

double fen(double x,double y, int n) {
double tmp = y;
double sum = 1;

for (int i = 1; i < n; i++) {
tmp *= -((x * y * (2*i-1)) / ((2*i) * (2*i+1) * (2*i+1)));
sum += tmp;
}

return sum;
}

int main(void) {
cout << fen(2,3,1) << endl;
cout << fen(2,3,2) << endl;
cout << fen(2,3,3) << endl;
cout << fen(2,3,4) << endl;
cout << fen(2,3,1000) << endl;
return 0;
}

我只检查了fen(2,3,4),并且结果在此之前都是正确的。它显示 fen(2,3,1000)0.162772:

1
0
0.18
0.161633
0.162772

更新:

更新了代码以使用 cout 进行输出,而不是 printf。但我认为此代码在 CC++ 之间并没有真正的区别。

此外,请记住,在此代码中,您很快就会达到 double 数值精度的限制。

关于c - 函数计算结果错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53065422/

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