[英]How to return a value from a for statement in a method in c#
我不明白為什么這段代碼不能在階乘方法中返回result
。 任何幫助,將不勝感激。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatorProgram
{
class Program
{
static void Main(string[] args)
{
Console.Write("What is the first number:\n> ");
decimal x = Convert.ToDecimal(Console.ReadLine());
Console.Write("What is the second integer:\n> ");
decimal y = Convert.ToDecimal(Console.ReadLine());
Console.Write("What is the operation that you would like to use?
Enter + , - , * , / , or ! :\n> ");
string operation = Console.ReadLine();
if (operation == "!")
{
Console.Write("Which number would you like to use?\n> ");
int num = int.Parse(Console.ReadLine());
Console.WriteLine("{0}! = {1}", num, Factorial(num));
}
}
private static int Factorial(int a)
{
int result;
for (int i = 1; i < a + 1; i++ )
{
result = a * i;
}
return result;
}
}
}
result = a * i;
是不正確的。
它應該類似於result = result * i;
, result
初始化為 1:即更改int result;
到int result = 1;
.
目前您正在評估a * a
。
試試這個:
private static int Factorial(int a)
{
int result = 1;
for (int i = 2; i < a + 1; i++)
{
result = result * i;
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.