gpt4 book ai didi

c++ - 为什么 for 循环在递增计数和递减计数时表现不同?

转载 作者:行者123 更新时间:2023-11-30 05:30:14 25 4
gpt4 key购买 nike

这是我最近重温的一道作业题。它要求我不要使用cmath 并编写一个函数来评估cos pi/3。代码是

#include <iostream>
using namespace std;

double power(double x, int b) {
if (b>1) return x*power(x,b-1);
else if (b==0) return 1;
else return x;
}

double cosine(double x, int k) {
double tmp=0;
for (int n=0; n<=k; n++) {
tmp += power(-1,n) / factorial(2*n) * power(x,2*n);
}
return tmp;
}

int main() {
double x=3.1415/3;
int k=100;
cout << cosine(x,k) << endl;
}

我用 for 循环编写了两个版本的 double factorial(int a)

一个加起来成功输出0.500027 :

double factorial(int a) {
double tmp=1;
for (int i=1; i<=a; i++) {
tmp*=i;
}
return tmp;
}

另一个倒计时输出inf(但成功求值4!=24):

double factorial(int a) {
double tmp=a;
for (int i=a; i>=1; i--) {
tmp*=i;
}
return tmp;
}

为什么倒计时循环无法给出收敛输出?

最佳答案

第二个 factorial()a 乘以两次。试试这个:

double factorial(int a) {
double tmp=1; // use 1 instead of a
for (int i=a; i>=1; i--) {
tmp*=i;
}
return tmp;
}

请注意,使用 double tmp=a; 并将 i 初始化为 a-1 并不好,因为它会使 阶乘(0) = 0,而 factorial(0) 应该是 1。

第一个实现也将 1 乘以两次,但乘以 1 不会影响结果。

关于c++ - 为什么 for 循环在递增计数和递减计数时表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36057448/

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