使用 out传值的时候仅仅是将变量名(箱子)拿过来,并不会管之前是什么值
函数体结束之前必须对该out的参数进行赋值,否则报错(不好意思还回去)
out传值,可以进行多个值的传回
public void Jia(int b,out int c)
{
c = b + 10;
}
Console.Write("请输入a=");
int a = int.Parse(Console.ReadLine());
int c = 4;
Program hanshu = new Program();
hanshu.Jia(a,out c);
Console.WriteLine(c);
Console.ReadLine();
//使用return如何返回多个值
public string fanhui()
{
return 1 + "-" + 2 + "-" + 5;
}
Program hanshu = new Program();
string[] array = hanshu.fanhui().Split('-');
int [] arr = new int[array.Length];
for (int i = 0; i < array.Length; i++)
arr[i] = int.Parse( array[i]);
}
函数练习:
{
1.求羊
每过一个村庄,卖掉之前总数的二分之一零一只
过了7个村庄之后还有两只
最初有多少只羊
//无参有返 public int assd() { int sum = 0; for (int i = 0; i < 7;i++ ) { if (i == 0) { sum = 2; } else { sum = 2 * (sum + 1); } } return sum; } static void Main(string[] args) { Program hanshu = new Program(); int s = hanshu.assd(); Console.WriteLine(s); Console.ReadLine();
2.掷骰子,投几走几步,逢3进1,逢5退1,逢7进2,逢0退4,求投几次后一共走了多少步?
//有参有返 public int bu(int s) { int bu = 0; Random ran = new Random(); for (int i = 0; i < s; i++) { int a = ran.Next(1, 7); bu += a; if (bu % 10 == 3) { bu += 1; } else if (bu % 10 == 5) { bu -= 1; } else if (bu % 10 == 7) { bu += 2; } else if (bu % 10 == 0) { bu -= 4; } else { continue; } } return bu; } static void Main(string[] args) { Program hanshu = new Program(); Console.Write("输入您投的次数:"); int x = hanshu.bu(int.Parse(Console.ReadLine())); Console.WriteLine(x); Console.ReadLine();
3.在一个箱子里有16个红球(编号1-16),3个蓝球(编号17-19),1个黄球(编号20),
随机抽取一个,抽中蓝球加4分,抽中黄球加7分,每抽中红球5次减2分,
抽几次后能达到100分
//无参有返 public string d() { Random ran = new Random(); int fen = 0; int i = 1; int c = 0; for (; ; ) { int s = ran.Next(1, 21); if (s < 17) { c++; if (c == 5) { fen -= 2; c = 0; } } else if (s < 20) { fen += 4; } else { fen += 7; } i++; if (fen >= 100) { break; } } return "需要" + i + "次,才能达到100分"; } static void Main(string[] args) { Program hanshu = new Program(); string s = hanshu.d(); Console.WriteLine(s); Console.ReadLine();