Reputation: 35
I am currently trying to prepare myself for an exam and I stumbled across the following assignment:
Compute the series (recursive and iterative) 1-(1/2)+(1/3)-(1/4)+(1/5)...(1/n). I searched the web in general and this page in particular but unfortunately I only found java-based solutions I didn't understand.
So, please help me :)
My best effort so far only gets me the answer "1.00" :-/
Here is what I did (in full):
#include <stdio.h>
float reihe_ite(int n);
float reihe_rek(int n);
int main(){
float a,b;
a=reihe_ite(5);
b=reihe_rek(5);
printf("\niterativ: %.2f\nrekursiv: %.2f", a, b);
return 0;
}
float reihe_ite(int n){
int i;
float x=0;
for(i=1;i<=n;i++){
if(i%2==0){
x=x-(1/i);
}
else{
x=x+(1/i);
}
}
return x;
}
float reihe_rek(int n){
if(n==1)
return 1;
else{
if(n%2==0){
return reihe_rek(n-1)-(1/n);
}
else{
return reihe_rek(n-1)+(1/n);
}
}
}
Upvotes: 0
Views: 110
Reputation: 145829
x=x-(1/i);
1/i
is an integer division.
Use:
x=x-(1.0f/i);
for a float
division
Upvotes: 2