Repeating function in c++

Hi,
I am trying to create a c++ program that will intake an original value of x_0 to begin a function that uses the previous value of x to calculate the one in question.
I.e.- f(x_0) = x_1, f(x_1) = x_2 and so on.
I understand that I will need to set up a loop using x = f(x) but am unsure how this is done exactly. The function being used is as follows: f(x) = a*sin(pi*x) where a and x_0 are the inputs. Any help would be great, thanks.
Try making f() a function that takes x and a as parameters and returns a*sin(pi*x). Prompt the user for x and a, then run a loop that assigns f(x, a) to x.
Pseudocode:
1
2
3
4
x = x_0
loop
x =f(x);
endloop


That is what you described, though I got a feeling that's not what you meant.
hanst99- yes this is what i meant, i wish to input x and a then run the loop but before doing so I need to create the function and this is what I am having trouble doing.
Did you try simply writing the function as it was given to you? It should work.
int f(int x, int a) { return a*sin(PI*x); }
PS: sin is defined in cmath, so you need to include that header.
 
#include <cmath> 


Also, PI is usually not defined, so you will have to do that yourself. Or just write 3.14.
Zhuge- I had the function included in the same way you suggested but when building I get an error saying a function-definition is not allowed here before "{" token.
Sounds like something wrong with more than just the function. Try posting your entire code if it isn't too long.
1 int main (){
2 int a,x;
3 cout<<"a=";
4 cin>>a;
5 cout<<"x=";
6 cin>>x;
7
8 int f(int x, int a) {
9 return a*sin(pi*x);
10 }
11
12 for (i=0; i<=20; i++){
13 x=f(x);
14 return f(x);
15 }
16 }

the errors occuring when compiling are:
a function-definition is not allowed here before "{" token (line 8)
"i" was not declared in the scope (line 12)
"f" was not declared in the scope (line 13)
Try using M_PI instead of PI, and remember #include <cmath>
@spurraldo:
Lines 8 to 10 should be outside int main() -you cannot define a function inside main();
ref: http://www.cplusplus.com/doc/tutorial/functions/

line 13: x = f(x) is not the correct way to call f() -it needs two integer paramaters
line 14: probably not what you intended, read the ref above.

Last edited on
matsom - thanks I moved lines 8 and 10 out of the main but it is now telling me that there are too few arguments in the part of the code that I moved?
What we told you earlier. You defined the function not as f(x), but as f(x,a), so you also need to pass it the second parameter a.
Topic archived. No new replies allowed.