View Full Version : Learning C, problem with an exercise.
medeshago
October 16th, 2008, 01:13 AM
I have to do the following:
Read a number and calculate the following sequence:
1-1/2+1/3-1/4+1/5...1/n
This is the way I'm doing it, but it doesn't work:
#include <stdio.h>
int main()
{
int a=0, n, suma=0;
float den;
printf ("\n Ingrese el número : ");
scanf ("%i", &n);
while (a<n)
{
if (a%2==0){
a++;
den=1/a;
suma-=den;}
else{
a++;
den=1/a;
suma+=den;}
}
printf ("\n Resultado secuencia = %i", suma);
return 0;
}
dmm1285
October 16th, 2008, 01:16 AM
if (a%2==0){
a++;
den=1/a;
suma-=den;}
else{
a++;
den=1/a;
suma+=den;}
}
}
Try switching your addition and subtraction like this.
medeshago
October 16th, 2008, 01:19 AM
Just did it, still not working.
Can+~
October 16th, 2008, 01:45 AM
Problem is, you're doing integer division:
1/2 = [0.5] = 0
1/3 = [0.33333..] = 0
1/4 = [0.25] = 0
To circumvent this issue, work with floats.
medeshago
October 16th, 2008, 01:50 AM
This is how it looks now:
#include <stdio.h>
int main()
{
int a=0, n;
float den, suma=0.0;
printf ("\n Ingrese el número : ");
scanf ("%i", &n);
while (a<n)
{
if (a%2==0){
a++;
den=1.0/a;
suma-=den;}
else{
a++;
den=1.0/a;
suma+=den;}
}
printf("%d", den);
printf ("\n Resultado secuencia = %d", suma);
return 0;
}
But this is what I get:
Ingrese el número : 5
Resultado secuencia = 536870912
Can+~
October 16th, 2008, 01:54 AM
Now you got a printing problem:
printf("%d", den);
printf ("\n Resultado secuencia = %d", suma);
Should be
printf("%f", den);
printf ("\n Resultado secuencia = %f", suma);
btw, here's my implementation (with for, and inverting sign)
int main(int argc, char** argv)
{
float total=0;
int count, sign=1, max=20;
for (count=1; count < max; count++)
{
total += sign*(1.0/count);
printf("%d : %.8f\n", count, total);
sign = -sign;
}
printf("%.8f", total);
return 0;
}
sign inverts each iteration, meaning that you don't need that "if" in between.
medeshago
October 16th, 2008, 02:07 AM
Thanks, man, now it works great.
Powered by vBulletin® Version 4.2.2 Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.