c#初学求指导
我是刚从C过渡到C#的,在字段定义的时候可能没有面向对象的严谨,请指导
以下编码是自己根据书中的练习题编制的,求优化!
题目:
用out参数实现以下功能。
有一群人同乘一条船,船漏,必须有人跳入水中减轻重量才能保持船不沉没,大家决定所有人围成一圈报数,报到7的人跳到水中,该人的下一人继续从1开始报数,依旧是报到7的跳入水中,如此重复直到所有人入水为止。
实现各位置入水次序。
自己的编码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ch5_6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class people
{
public void getjumpnum(int personnum, out int[] jumpnum)
{
jumpnum = new int[personnum+1];//定义personnum数组
int i,n=0, flag=0,k=1;
int[] j = new int[personnum + 1];//定义局部变量
for (i = 1; i <=personnum; i++)
{
j[i] = 1;//表示该位置上未跳水
}
for (i = 1; i <= personnum+1; i++)
{
if (i == personnum+1)//当i超过人数,给i初始化1
i = 1;
flag += j[i];
if (flag == 7)
{ n++; j[i] = 0; jumpnum[k++] = i; flag = 0; }// j[i] = 0表示该位置上跳水, jumpnum[k++] = i记录位置,flag初始化
if (n == personnum)//n来控制循环
break ;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
int i, personnum;
int[] p;
people jump = new people();
personnum = Convert.ToInt16(textBox1.Text);
jump.getjumpnum(personnum, out p);
for (i= 1; i <= personnum;i++ )
{
textBox2.Text = textBox2.Text + " " + p[i].ToString();
}
}
}
}
void SortIt(int _num, int[] its, out ArrayList _jumpSort)
{
_jumpSort = new ArrayList();
int i = 0, j = 0;
while (_jumpSort.Count != its.Length)
{
j = (j == its.Length) ? 0 : j;
if (its[j] == -1)
{
j++;
continue;
}
if (i == _num)
{
i = -1;
its[j] = -1;
_jumpSort.Add(j);
}
i++;
j++;
}
}