编写一个计算n的子程序.使用此子程序时,制作一个计算(a+b)的程序

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

本文关键字:一个 计算 子程序 a+b 程序      更新时间:2023-10-16

我的任务是

编写一个计算n!的子程序。在使用此子程序时,制作一个计算CCD_ 2的程序。

我写了以下代码:

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;
}

当我编译时,我得到了这个错误:

 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

这是您的错误

return f;

返回函数f()的函数指针。此外,您还在使用函数指针进行计算。

在C++中,您需要声明一个可用于计算和返回的变量:

int f(int n) {
    int result = 1;
    for(int i=1;i<=n;i++) { 
        result=result*i;
    }
    return result;
}
相关文章: