2015-06-28 34 views
1

在我的C++ OOP类中收到以下赋值。在C++中使用类对C语言进行编码

将以下用于计算Factorial的过程程序转换为使用类来计算Factorial的程序。

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

使用下面的驱动程序的。一个驱动程序意味着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 
} 
+3

'#include '如果你在C++课程中给出这个,请将你的钱退回来。正确的标题是'' – PaulMcKenzie

+0

哦,是的,这个“教授”实际上是最差的,但我需要这个班才能转学,而且这是我学校唯一的教授。他的在线课程比你必须真正出现并听到他讲课的版本要糟糕得多,但他的代码非常难以置信,因此几乎不可能在现实世界中做好任何实际的编码准备。 – Astrophysicsgrrl

回答

1

通过

class factorialClass 
{ 
}; 

创建factorialClass类现在添加计算阶乘的功能。 FactNum(int)

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

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

+0

谢谢。这清理了我的东西。非常感激! – Astrophysicsgrrl

2

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

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

功能不做投入,他们的论点。