helping please!

could someone solve this question?

 
  it is my homework.I am not good at c++ functions.Please help me.

The function s(n) returns the sum of the first n terms of 1 + 1/2 + 1/4 + 1/8 + ... . Write a program to input
the integer n and output the result s(n). The object s(n) should be implemented as a function.
Last edited on
http://www.cplusplus.com/doc/tutorial/functions/

:) This should help you my good sir!
You get and do homework to become good at c++ functions.

You need input and output. See http://www.cplusplus.com/doc/tutorial/basic_io/
You need a loop. See http://www.cplusplus.com/doc/tutorial/control/

Make an effort and show some code. Then we can point out where you went haywire.
Heres some sample code to help you along the way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 
#include "std_lib_facilities.h" // this is just iostream and stuff.

// WARNING: THIS PROGRAMS CONTAINS AWFUL FUNC/VAR NAMES

double s(double); //prototype our func for use
double sum = 0;

int main()
{
    cout << s(3) << '\n'; // this should output 1.75
    return 0;
}

double s(double n)
{
    double val = ?; // what should we be starting our variable off with?
    for(int i=0; i < ?; i++) // think - we want to loop how many times again? 
    {
        sum += ?; // what variable are we adding each iteration? 
        val /= ?; // we want half the value each iteration 
    }

    return ?; // what are we giving back at the end? 
}


I basically just wrote your program the rest is technical detail. You need to practice this stuff more to ensure you're understanding the code you write :)

Last edited on
Topic archived. No new replies allowed.