PDA

View Full Version : in need of assistance (c++)


snoopy
10-07-2005, 03:35 AM
hello

i am new to "coding" forums, i am currently venturing into the world of c++ and would greatly appreciate any advice on a current problem i am working on.

thanks.

i am trying to write a program that caclulates the sum of hte first N terms of Zeno's series (1/2 + 1/4 + 1/8 + 1/16 +..... = 1) where the denominators are powers of two. by inputing an integer between 1 and 15, my program should print N terms of the series separated by + signs, followed by the = sign, followed by the value of the sum.

my logic is as follows: not do the actual division until the "=" has been
printed out, and to use two counters. One of them just keeps track of how
many iterations of the loop i've gone through, and the other starts at
2 and actually multiplies by 2 each time. When the loop is done, then
divide by the second counter to get the floating point answer. To print out the computation, only print the 2, 4, 8, etc as an actual number. The 1/ can be just part of the string. i'll have to print out a "+" between each fraction.

now the tough part, being new to c++, i am in great need on the coding......before I show you what i have so far, please refrain from laughing!

#include <iostream>
#include <cmath>
using namespace std;
int main()
{

int m, n;
double i;

int i =1;

cout << "This program computes the sum of the first N terms of Zeno's\n";
cout << "series, where N is a number between 1 and 15 (inclusive).\n";
cout <<endl;
cout << "Please enter a number between 1 and 15 (inclusive): ";
cin >> n;

if ((n < 1) || (n > 15))
cout << "Invalid entry!\n";
else
{
double count = 0;
double sum = pow(1/2, n);
while (count <= n)
{
m = pow(2, i);
sum += pow(1/2, i);
if (n = 1)
cout << "1/2 = " << sum <<endl;
}
cout <<endl;
cout << sum <<endl;

cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(6);
}

return 0;
}

tricolaire
10-07-2005, 04:12 AM
I can tell you right off your gonna have problems compiling with the variable i. you have it defined as both an integer and a double.

I'll take a more indepth look later

rpgfan3233
10-07-2005, 05:09 AM
Here's the easiest way I could think of:
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
double sum = 0.0;
int n;

cout << "This program computes the sum of the first N terms of Zeno's\n"
<< "series, where N is a number between 1 and 20 (inclusive)."
<< endl << endl;
cout << "Please enter a number between 1 and 20 (inclusive): ";
cin >> n;

for (double i = 1.0; i < n; i++)
{
if (sum >= 1) break;
sum += pow(0.5, i);
}
cout.precision(6);
cout << sum << endl;
return 0;
}