-4

My task is

Write a subprogram that calculates n!. While using this subprogram make a program that calculates (a+b)!.

I wrote the following code:

using  namespace  std;
int f(int n) {
    for(int i=1;i<=n;i++){
        f=f*i;
    }
    return f;
}
int main() {
    int a,b;
    cout<<"a=";
    cin>>a;
    cout<<"b=";
    cin>>b;
    cout<<"factorial of a+b="<<(a+b)*f;
    return 0;
}

And I get this error when I compile:

 In function 'int f(int)':
7:27: error: invalid operands of types 'int(int)' and 'int' to binary 'operator*'
8:8: error: invalid conversion from 'int (*)(int)' to 'int' [-fpermissive]
 In function 'int main()':
16:34: error: invalid operands of types 'int' and 'int(int)' to binary 'operator*'
17:9: error: expected '}' at end of input
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
uniqxx
  • 13
  • 4
  • 1
    Look at the error messages again. Look at the code where `f` is used. Look at the code where `f` is defined. Do that a few times and I'm sure you will see the problem. – Some programmer dude Jan 07 '16 at 14:42
  • Some indentation in your code would be helpful. – NathanOliver Jan 07 '16 at 14:42
  • to elaborate on Joachim comment, f in defined as a function and you use it as an int in the loop, as well as return f!! – apomene Jan 07 '16 at 14:44
  • From your definition of `f`, and the expression `(a+b)*f`, I would suggest that you get a [good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). If you already have one, open it and read it again. Pay particular attention to the text that isn't code, as it explains the code. – molbdnilo Jan 07 '16 at 14:55
  • Welcome to linear algebra, where functions are matrix and calling a function is multiplying :D. – YSC Jan 07 '16 at 15:24

1 Answers1

1

Here's your error

return f;

returns a function pointer of your function f(). Also you're using the function pointer for your calculations.

In C++ you need to declare a variable that can be used to calculate and return:

int f(int n) {
    int result = 1;
    for(int i=1;i<=n;i++) { 
        result=result*i;
    }
    return result;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190