我正在尝试编写一个递归代码,用于计算给定数字的阶乘。 (3的因子是" 3 * 2 * 1 = 6")。我编写了以下代码,并打印以下错误消息
"无效的令牌'('在类,结构或界面成员声明中"
我检查了我的代码,在我看来,我看不到错误,有什么办法可以解决这个问题吗? c#代码发布在下面。 (ps。我不是c#wizz。)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
int num1;
int num2;
int num3 = 0;
Console.WriteLine("Insert number");
num1 = Console.ReadLine();
num2 = num1 -1;
factorial(num1, num2, num3);
Console.WriteLine("Your number is {0}", factorial());
}
Console.ReadKey();
static int factorial(int a, int b, int c)
{
if (a > 0)
{
a * b = c;
factorial(a - 1, c, c);
return c;
}
}
}
}
答案 0 :(得分:3)
您有Console.ReadKey();
外部方法声明。将其移至public static void Main(string[] args)
即可。
答案 1 :(得分:2)
它不喜欢Console.WriteLine("Your number is {0}", factorial());
你的阶乘函数有3个参数,你从未声明过没有参数。
您需要保留结果并显示它。
如果您感兴趣,还有一些方法可以改善您已经实现的实际因子例程
答案 2 :(得分:1)
您的代码存在许多问题,并且无法编译,让我们完成每个错误
无效的令牌'('在类,结构或接口成员声明中
正如其他答案所指出的那样,除了任何方法之外,你的班级中间的Console.Readkey()
。将其移到Main
方法的底部。
无法隐式转换类型'字符串'到' int'
这是由于行num1 = Console.ReadLine();
,因为该方法返回一个字符串,并且您尝试将其分配给int。 正确处理此问题的方法是检查用户输入,以确保他们输入了数字。为了简洁起见,我将错误这样做,并假设它正确。
num1 = int.Parse(Console.ReadLine()); // Use TryParse here, and notify the user if they typed something wrong
没有超载方法' factorial'取0个参数
这是因为您尝试在没有参数的情况下调用factorial
方法。我想你试图输出上面调用的结果。
var result = factorial(num1, num2, num3);
Console.WriteLine("Your number is {0}", result);
类型或命名空间名称' a'找不到(你错过了使用指令或汇编引用吗?)
这是由于这一行:a * b = c;
这是没有意义的。我认为你的意思是c = a * b;
最后
' Rextester.Program.factorial(int,int,int)':并非所有代码路径都返回值
您需要返回if
factorial
之外的值。然后你进入无限循环,但至少你的代码编译!现在只需修复你的算法。这更简单
static int factorial(int n)
{
if(n == 1)
return 1;
return factorial(n-1) * n;
}
实例:here