练习: C#---函数(三角形、卖羊、兔子生兔子)
/// <summary> /// 打印三角形
/// </summary> public void Sanjiao() { Console.Write("请输入行数:"); int a = int.Parse(Console.ReadLine()); for (int i = 1; i <= a; i++) { for (int j = 1; j <= i; j++) { Console.Write("@"); } Console.WriteLine(); } Console.ReadLine(); } static void Main(string[] args) { Program hanshu = new Program(); hanshu.Sanjiao(); Console.ReadLine();
}
/// <summary> /// 输入一个参数,自动打印三角形 /// </summary> /// <param name="a"></param> public void Sanjiao(int a) { for (int i = 1; i <= a; i++) { for (int j = 1; j <= i; j++) { Console.Write("@"); } Console.WriteLine(); } Console.ReadLine(); } static void Main(string[] args) { Program hanshu = new Program(); Console.Write("请输入行数:"); int a = int.Parse(Console.ReadLine()); hanshu.Sanjiao(a); Console.ReadLine(); } } }
/// <summary> /// 每过一个村卖掉一半零1只羊,过了7个村,还剩2只羊,问最初多少只羊 /// </summary> /// <returns></returns> public int sheep() { int sum = 0; for (int v=7;v>=0;v--) { sum = 2 * (sum + 1); Console.WriteLine("第"+v+"个村" + "有"+sum+"只羊"); } return sum; } static void Main(string[] args) { Program hanshu = new Program(); Console.WriteLine("最初有"+hanshu.sheep()+"只羊"); Console.ReadLine(); } } }
/// <summary> /// 一对幼兔,一个月后长成小兔,小兔一个月后长成成兔并生下一对幼兔, /// 成兔每月生下一对儿幼兔,问多少天后有多少只兔子。 /// </summary> /// <param name="days"></param> /// <returns></returns> public int rabbit(int months) { int sum=0; int yt = 1; int xt = 0; int ct = 0; for (int i = 1; i <= months;i++ ) { ct = ct + xt; xt = yt; yt = ct; sum = yt + xt + ct; Console.WriteLine(i + "个月后幼兔" + yt + "对,"+"小兔" + xt + "对,"+"成兔"+ ct + "对,"+"共"+sum+"对");
}
return sum; }
static void Main(string[] args) { Program hanshu = new Program();
Console.Write("请输入月数:");
int a = int.Parse(Console.ReadLine());
Console.WriteLine(a+"个月后兔子共有"+hanshu.rabbit(a)+"对"); Console.ReadLine(); }