繁体   English   中英

如何用C ++编写阶乘程序

[英]How to make a factorial program in C++

我是这个网站的新手; 实际上,这是我的第一个问题。 因此,如果我在错误的背景下提出此问题,请通知我,以便我进行调整。 我有一个在Visual Studio 2010中创建的程序,允许用户输入1到10之间的整数。该用户将单击一个按钮,该按钮应依次计算并在文本框中显示整数的阶乘值。 我以为一切看起来都正确,但是文本框中什么也没出现。

以下代码是我一直在使用的代码:

#pragma endregion
        private: System::Void btnFactorial_Click(System::Object^  sender, System::EventArgs^  e) 
        {
            int n;
            int nfact = 1;
            Int32::TryParse(txtNum->Text, n);
            if (n > 0)
            {
                for (int i = 1; i <= n; i++)
                    nfact *= i;
                txtResult->Text = nfact.ToString();
            }
            else
                MessageBox::Show ("Please enter a value > 0");      
        }

        private: int Factorial (int n)
        {
            if (n == 0)
                return 1;
            else
                return n * Factorial (n-1);
        }
    };
}

我可以在这里做错什么吗?

您需要在某个地方调用自己的函数。 替换为:

for (int i = 1; i <= n; i++)
                nfact *= i;

并写成这样:

nfact = Factorial(n);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM