要求输入的数在1-20 ; 输入一个数 ,求其阶乘
这是小生我的 ;老师看看错在那儿了
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
int c;
c = Convert.ToInt32(Console.ReadLine());
getways.jiecheng(c);
Console.WriteLine(getways.z);
}
}
class getways
{
public static int z;
public static int jiecheng(int x)
{
if (x > 20)
{
Console.WriteLine("cuowu");
}
if (x == 1)
{
return x;
}
z = x * getways.jiecheng(z - 1);
return z;
}
}
}
z = x * getways.jiecheng(z - 1);
改成
z = x * getways.jiecheng(x - 1);
没看出用递归的必要性
也没看出定义一个类,以及一个叫z的成员的意义
你这么写,反倒画蛇添足,除了danielinbiti说的问题,还有一个问题,就是z在调用完后没有被重置,如果你调2次jiecheng又错了。
写程序的目的就是解决问题,用最简单的方式。
static class MathUtil
{
public static int Power(int n)
{
if (n > 20) throw new Exception("paramater great than 20")
if (n == 1) return 1;
int r = 2;
for (int i = 3; i < n; i++) r *= i;
return r;
}
}
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string str=string.Empty;
long lngNumber=0;
FactorialObject fo=new FactorialObject();
Console.WriteLine("Please input a number!");
str=Console.ReadLine();
if(string.IsNullOrWhiteSpace(str) || !long.TryParse(str,out lngNumber))
{
Console.WriteLine("Please input a valid number! ");
}
if(lngNumber<20)
{
Console.WriteLine("The number should be less than 20!");
}
Console.WriteLine("The Factorial of number {0} is {1}",lngNumber,fo.Factorial(lngNumber));
Console.ReadLine();
}
}
public class FactorialObject
{
public long Factorial(long l)
{
long lResult = 0;
if (l.Equals(1))
{
lResult = 1;
}
else
{
lResult = l * Factorial(l - 1);
}
return lResult;
}
}
}
按照楼主的要求改写了一下,VS2013下测试通过,楼主看一下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
int c;
c = Convert.ToInt32(Console.ReadLine());
getways.jiecheng(c);
Console.WriteLine(getways.z);
Console.ReadKey();
}
}
class getways
{
public static long z; //在本例中,z可以放在这里,但是这样做不好,容易引起混乱.可以把z放在函数内,Main输出时直接输出jiecheng的函数结果
public static long jiecheng(int x)//实际执行结果,如果用int的话会溢出,导致结果不正确
{
if (x > 20)
{
Console.WriteLine("cuowu");
return 0;//如果这里不返回,那么虽然报了错误,但是程序还会继续执行下去。
}
if (x == 1)
{
return x;
}
z = x * getways.jiecheng(x - 1);//你是计算的x的阶乘,所以要用x为参数来递归。
return z;
}
}
}