use*_*941 0 c# console-application
我试图得到一个因子显示为例如(5的阶乘是5*4*3*2*1)
我正在使用factorial的方法,但它不接受Console.Write(i + " x ");我的代码中的行.
任何帮助都会很棒.这是我的代码.
//this method asks the user to enter a number and returns the factorial of that number
static double Factorial()
{
string number_str;
double factorial = 1;
Console.WriteLine("Please enter number");
number_str = Console.ReadLine();
int num = Convert.ToInt32(number_str);
// If statement is used so when the user inputs 0, INVALID is outputed
if (num <= 0)
{
Console.WriteLine("You have entered an invalid option");
Console.WriteLine("Please enter a number");
number_str = Console.ReadLine();
num = Convert.ToInt32(number_str);
//Console.Clear();
//topmenu();
//number_str = Console.ReadLine();
}
if (num >= 0)
{
while (num != 0)
{
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
}
Console.Write(i + " x ");
Console.Clear();
Console.WriteLine("factorial of " + number_str.ToString() + " is " + factorial);
factorial = 1;
Console.WriteLine("(please any key to return to main menu)");
Console.ReadKey();
Console.Clear();
topmenu();
}
}
return factorial;
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
问题是你的for循环没有使用大括号,所以范围只是一行.
尝试适当添加大括号:
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
Console.Write(i.ToString() + " x ");
}
Console.WriteLine("factorial of " + number_str.ToString() + " is " + factorial);
Run Code Online (Sandbox Code Playgroud)
如果没有大括号,i变量只存在于下一个语句(factorial = factorial * i;)中,并且在您调用时不再存在于作用域中Console.Write.
你可能还想删除Console.Clear紧随其后的电话Write,否则你将看不到它.