首页 > 解决方案 > 为什么类的函数没有在主函数中被调用?

问题描述

我想创建一个计算整数阶乘的类,我的代码搞砸了,我需要一些方向......你能帮我找到问题吗?

#include <iostream>

class fact {
private:
    int a;
public:
    fact(){};
    fact(int a){this->a=a;}
    void setfact(int a){this->a=a;}
    int getfact(){return a;}

    int Fact(){
        int i;
        if (a>0){
          for(i=2;i<=a;i++){
            return a=a*i;
          }
        }
        else if (a=0)
            return 1;
        else
            return 0;
     }
};

using namespace std;

int main()
{
    fact b;
    int j;
    cout << "entrer un nombre pour calculer sa factorielle" << endl;
    cin >> j;

    Fact b(j);

    cout << "la factorielle de" << j << "est:" << b.Fact(j);
    return 0;
}

标签: c++class

解决方案


感谢您的帮助,现在我的代码完美运行......不管变量和声明的汤哈哈。

#include <iostream>
using namespace std;

class fact{
private:
    int a;
public:
    fact(){};
    fact(int a){this->a=a;}
    void setfact(int a){this->a=a;}
    int getfact(){return a;}

    int Fact(int a){
        int i;
        int res=1;
        if (a>0){
            for(i=2;i<=a;i++){
                res=res*i;
            }
          return res;
            }

        else if (a==0)
            return 1;

        else
            return 0;
            }
};


int main()
{

    int j;
    std::cout << "entrer un nombre pour calculer sa factorielle" << endl;
    std::cin >> j;
    fact b(j);

    cout << "la factorielle de " << j << " est: " << b.Fact(j);
    return 0;
}

推荐阅读