[英]Why does std::begin behave differently when called in a nested function
[英]Why does for-loop behave differently when counting up vs counting down?
這是我最近重新審視的作業問題。 它要求我不要使用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
不好,因為它會使factorial(0) = 0
,而factorial(0)
應該是 1。
第一個實現也乘以 1 兩次,但乘以 1 不會影響結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.