c#函数及out传值
使⽤ 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)
writeline函数
{
Program hanshu = new Program();
string s = hanshu.d();
Console.WriteLine(s);
Console.ReadLine();
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论