在我的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
}
'#include'如果你在C++課程中給出這個,請將你的錢退回來。正確的標題是'' –
PaulMcKenzie
哦,是的,這個「教授」實際上是最差的,但我需要這個班才能轉學,而且這是我學校唯一的教授。他的在線課程比你必須真正出現並聽到他講課的版本要糟糕得多,但他的代碼非常難以置信,因此幾乎不可能在現實世界中做好任何實際的編碼準備。 – Astrophysicsgrrl