使用类对C++中的阶乘进行编码

Coding for Factorials in C++ using classes

本文关键字:阶乘 编码 C++      更新时间:2023-10-16

在我的C++OOP类中收到以下赋值。

将以下计算阶乘的过程程序转换为使用类计算阶乘。

#include <iostream.h>
int factorial(int);
int main(void) {
    int number;
    cout << "Please enter a positive integer: ";
    cin >> number;
if (number < 0)
    cout << "That is not a positive integer.n";
else
    cout << number << " factorial is: " << factorial(number) << endl;
}
int factorial(int number) {
    int temp;
    if(number <= 1) return 1;
    temp = number * factorial(number - 1);
    return temp;
}

使用以下驱动程序。Driver程序意味着int main()。。。已经为您编写了。您只需要创建类并将其添加到代码中。

提示:查看下面代码中使用的类的名称(factorialClass),然后查看下面使用的方法/函数名称(FactNum)。。你的新班级必须使用它们。。。

int main(void) {
 factorialClass FactorialInstance;  //
 cout << "The factorial of 3 is: " << FactorialInstance.FactNum(3) << endl;
 cout << "The factorial of 5 is: " << FactorialInstance.FactNum(5) << endl;
 cout << "The factorial of 7 is: " << FactorialInstance.FactNum(7) << endl;
 system("pause");  // Mac user comment out this line
}

我自己做得还可以,但我收到了一堆错误消息,我不确定我错过了什么。我在网上发现了很多其他的代码块,可以很容易地创建阶乘程序,但我不确定如何将其与他喜欢的驱动程序代码集成。以下是我迄今为止所掌握的信息。

#include <iostream>
using namespace std;
class factorialClass{
    int f, n; 
    public: 
    void factorialClass::FactorialInstance();
{
f=1;
cout<<"nEnter a Number:";
cin>>n;
for(int i=1;i<=n;i++)
    f=f*i;
}
}
int main(void) {
 factorialClass FactorialInstance;  //
 FactorialInstance.FactNum();
 cout << "The factorial of 3 is: " << FactorialInstance.FactNum(3) << endl;
 cout << "The factorial of 5 is: " << FactorialInstance.FactNum(5) << endl;
 cout << "The factorial of 7 is: " << FactorialInstance.FactNum(7) << endl;
 system("pause");  // Mac user comment out this line
}

这是一个愚蠢的任务。阶乘函数不是对象的适当成员,但要完成main的要求,它看起来像:

struct factorialClass{
  int FactNum(int number = 1) {  // default argument helps with the first call
    if(number <= 1) return 1;
    return number * FactNum(number - 1);
}

函数不做输入,它们做参数。

通过创建类factorialClass

class factorialClass
{
};

现在添加函数来计算阶乘。FactNum(int)

class factorialClass
{
public:
     int FactNum(int x)
     {
        //code to compute factorial
        //return result
     }
};

使用驱动程序类进行测试。