使用类对C++中的阶乘进行编码
Coding for Factorials in C++ using classes
在我的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
}
};
使用驱动程序类进行测试。
相关文章:
- 在 C++ 中的数组上使用阶乘函数
- 阶乘问题在 c++ 中给出错误的输出
- 大数的阶乘给出错误的输出
- 什么模板用法在阶乘中更好
- 为什么我在C++阶乘函数中出现编译错误?
- 计算阶乘的 C++17 倍表达式中的错误
- 为什么 Lisp 中 1000 阶乘的计算如此之快(并显示正确的结果)?
- 在C++中执行 N 阶乘编译时间的 3 种不同/相同方法
- 平方模型为零,阶乘模型问题
- 阶乘元规划
- 阶乘-c++ 我想以不同的方式打印
- 阶乘函数只返回C++中输入的答案
- 阶乘使用循环递增给出垃圾值
- 大 n 表示阶乘
- 为什么我不能在非常量表达式上使用此模板阶乘函数?
- 计算最大数字的阶乘
- 这个阶乘程序内部发生了什么?
- 返回阶乘C++的递归函数
- C++ 中是否有任何内置阶乘函数?
- 使用类对C++中的阶乘进行编码