我尝试在执行for循环时尝试添加总和,如果这有意义吗?比如:
float a = 0;
int main(){
float sum = 0;
for(int n = 1; n < 100; n++){ //n increases everytime
sum = (1.0/(n * (n+1.0)));
a = sum;
cout << a << endl;
}
我如何看待&#39; a&#39;当n = 1时,将其加到&#39; a&#39;当n = 2时,那么继续这样做?然后取两个&#34; a&#39; s&#34;并在n = 3时添加它?对不起,如果它有点令人困惑,因为我自己并没有真正得到它...如果有帮助,这里有一个例子:
(1/(1*2)) + (1/(2*3))+ (1/(3*4))+...(1/(n*(n+1)))
答案 0 :(得分:4)
您似乎需要此代码:
float a = 0;
for(int n = 1; n < 100; n++){ //n increases everytime
sum = (1.0/(n * (n+1.0)));
a += sum;
}
cout << a << endl;