注册 登录
编程论坛 C++教室

菜鸟请教个问题 用类写计算阶乘的程序

spikespiegel 发布于 2010-11-06 15:10, 549 次点击
额 我是新手 刚学面向对象 这个程序能编译的出来 你们可以试试嘛 但是运行以后在输入阶乘数目的地方它就溢出了 我对类的构造函数的用法不太熟悉 不知是哪里出了问题 请前辈们看下

这是目前正确的写法

#include "stdafx.h"
#include <iostream>
#include "stdlib.h"


using namespace std;

class calculate
{
public:
    int input;
    int times, i;
    int number;

    calculate()
    {
        times = 0;
    }

    calculate(int newtimes)
    {
        times = newtimes;
    }

    double sum(int input)
    {
        if (input == 0)
            return 1;
        else
            return input * sum(input - 1);
    }

    void loop(int times)
    {
        cout << "how many times do you want to calculate the sum?";
        cin >> times;
        for (i=0;i<times;i++)
        {
            cout << "please input a number: ";
            cin >> number;
            while(number < 0)
            {
                cout << "please input the number again." << endl;
                cin >> number;
            }
                cout << "the number " << i+1 << " digit is " << number << " ,the result is: " << sum(number);
                cout << endl;
        }
    }
};

int main()
{
    int times = 0;
    calculate cal;
    cal.loop(times);
    system("pause");
    return 0;
}

[ 本帖最后由 spikespiegel 于 2010-11-8 18:14 编辑 ]
4 回复
#2
burellow2010-11-06 17:01
神马问题?
#3
ou11112010-11-06 17:13
楼主写的看不懂,你想表达什么,类里面全是公有成员,在主函数直接就能访问了
#4
spikespiegel2010-11-06 19:48
哦 我知道哪里出错了
    int sum(int input)
    {
        if (input = 0)
            return 1;
        else
            return input * sum(input - 1);
    }

这个函数里input的表达式应该是==不是=
#5
pangding2010-11-06 20:20
回复 4楼 spikespiegel
呵呵,自己动手丰衣足食~~
1