Click here to Skip to main content
16,023,224 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Consider the function sum(n)= 1+1/5 +1/10 +… +1/5n .
Write a nonrecursive version of sum(n). Use it to calculate sum(100).
Here's the code:

C++
#include <iostream>
using namespace std;
double suma (int   n);

void main ()
{ 
	int n;
	cout<<"Enter an integer n to calculate sum(n)= 1+1/5 +1/10 +… +1/5n  \n";
	cin>>n;
	cout<<"The sum ("<<n<<") is "<<suma(n)<<endl;
}
double suma (int a)
{
	int i, sum=0;
	for (i=1 ; i<=a; i++)
	{
		sum += (1/(5*i));
	}
	return sum+1;
}
Posted
Updated 28-Mar-10 11:16am
v3

1 solution

7mesho wrote:
sum += (1/(5*i));


1 divided by 5 is less than 1. As i increases, your number gets closer and closer to 0, and as it starts at .2, and because you're using int and not float or double, the values in the loop that get added to sum keep getting rounded down to 0. You are returning a double, but inside the method you're using int, you need to use double inside your method also.

If you learned how to use the debugger, and stepped through your code, this would have been apparent to you in no time.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900