在while循环中向Array添加一个值
本文关键字:一个 添加 循环 while Array | 更新日期: 2023-09-27 18:05:22
我正在制作一个程序来运行斐波那契数列。我创建了2个数组。
-
第一个数组只包含0,1(数组名称:- int[] arr)
-
第二个数组保存其他值,例如:1,2,3,5 ..........etc (Array Name:- int[] numbers)
我使用while循环来获取febonacci级数并将其存储在第二个称为int[]数字的数组中。
在使用while循环获取值后,我使用
连接两个数组int[] final = arr.Concat(number).ToArray();
最后,我使用foreach循环将febonacci级数添加到列表框中。
我的问题是,我不能连接两个数组。我试图在while循环的顶部分配数字数组。所以这个number变量可以在while循环之外访问。但是我得到一个错误。
请看下面的代码:
private void button1_Click(object sender, EventArgs e)
{
int x = 0;
int y = 1;
int z = 0;
if (!String.IsNullOrEmpty(q1input.Text))
{
int value;
if (int.TryParse(q1input.Text, out value))
{
int[] arr = {x, y };
while (z < value)
{
z = x + y;
int[] number = {z};
x = y;
y = z;
}
int[] final = arr.Concat(number).ToArray();
foreach (int num in final)
{
q2listbox.Items.Add(num);
}
}
else
{
MessageBox.Show("It is not a numeric value");
}
}
else
{
MessageBox.Show("Invalid Input");
}
}
List<int> number = new List<int>();
while (z < value)
{
z = x + y;
number.Add(z);
x = y;
y = z;
}
int[] final = arr.Concat(number).ToArray();
如果您分离您的关注点可能会有所帮助:计算斐波那契数列应该与您的用户界面代码分开。
你的部分问题是你在c#中使用数组(固定长度)构建长度可调的东西。List<T>
是一个更好的数据结构。尽管它的名字具有误导性,但它是一个可调整长度的数组,而不是计算机科学意义上的实际列表。
生成斐波那契数列并不像你想象的那么复杂。这个实现:
public int[] FibonacciSequence( int x1 , int x2 , int upperBound )
{
if ( x1 < 0 ) throw new ArgumentException("x1 can't be negative") ;
if ( x2 < 0 ) throw new ArgumentException("x2 can't be negative") ;
if ( x1 == 0 && x2 == 0 ) throw new ArgumentException("x1 and x2 can't both be zero.") ;
List<int> values = new List<int>() ; // use List<int>, since we don't know the length in advance
values.Add(x1) ; // the first 2 elements are given
values.Add(x2) ;
// the remaining elements are computed by summing the previous two elements and shifting.
for ( int x = x1+x2 ; x > 0 && x < upperBound ; x = x1+x2 )
{
// add the new value to the list of values
values.Add(x) ;
x1 = x2 ; // x1 receives x2 (with the current x1 shifting off into oblivion
x2 = x ; // x2 receives x
}
int[] sequence = values.ToArray() ;
return sequence ;
}
斐波那契数列从[0,1]或[1,1]开始没有规则,只是惯例。然后你可以用你想要的种子来调用这个函数,这样:
int[] fibonacci = FibonacciSequence(1,1,int.MaxValue) ;
斐波那契数列很酷的一点是,不管种子值是多少,序列越长,任意两个相邻值的比值都会趋近于phi,也就是黄金平均数。
更容易的是使用LINQ的一些功能和魔力。使用它,您的斐波那契序列变得更加简单:
public IEnumerable<int> FibinacciSequence( int x1 , int x2 )
{
yield return x1 ;
yield return x2 ;
for ( int x = x1+x2 ; x > 0 && x < int.MaxValue ; x = x1+x2 )
{
yield return x ;
x1 = x2 ;
x2 = x ;
}
}
它的用法是这样的:
int[] sequence = FibonacciSequence(1,1)
.TakeWhile( x => x < upperBound )
.ToArray()
;
你甚至可以跳过' ToArray()
位,直接写
foreach ( int value in FibonacciSequence(1,1).TakeWhile( x => x < upperBound ) )
{
q2listbox.Items.Add( value ) ;
}
,当您将每个值添加到列表框中时,它将以惰性方式计算序列。