Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

c# - For loop to calculate factorials

Currently I have this set of code and its meant to calculate factorials.

int numberInt = int.Parse(factorialNumberTextBox.Text);

for (int i = 1; i < numberInt; i++)
{
  numberInt = numberInt * i;
}

factorialAnswerTextBox.Text = numberInt.ToString();

For some reason it doesn't work and i have no clue why. For example i will input 3 and get the answer as -458131456 which seems really strange.

Any help appreciated. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
int numberInt = int.Parse(factorialNumberTextBox.Text);
int result = numberInt;

for (int i = 1; i < numberInt; i++)
{
    result = result * i;
}

factorialAnswerTextBox.Text = result.ToString();

on a side note: this would normally NOT be the correct way to calculate factorials. You'll need a check on the input before you can begin calculation, in case your starting value is 1 or below, in that case you need to manually return 1.

On another side note: this is also a perfect example of where recursive methods can be useful.

int Factorial(int i)
{
    if (i <= 1)
        return 1;
    return i * Factorial(i - 1);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...