2015-06-28 23 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); 
} 

功能不做投入,他們的論點。