首页 > 解决方案 > 为什么我的 C# 代码不能按预期工作(数组转换,新手)

问题描述

我正在尝试获取数字数组(仅限 0 或 1)并反复对其进行转换,如下所示:

例如,如果数组大小为 10 并且以全零开头,则程序应输出以下内容:

0000000000
0111111110
0011111100
0001111000
0100110010
0000000000
0111111110
...and so on 

我写了一个应该这样做的代码,但它没有按预期工作。它总是首先完美地进行转换,然后开始一些错误的、不对称的、疯狂的东西:

0000000000
0111111110
0000000000
0101010100
0000000010
0101010000

是什么让我的代码的行为方式如此?

这是代码:

namespace test
{
    class Program
    {
        public static void Main(string[] args)
        {
            const int leng = 10; //length of array
            int[] arrayone = new int[leng]; 
            int[] arraytwo = new int[leng];
            for (int i = 0; i<=leng-1; i++)
            {
                arrayone[i] = 0;
                arraytwo[i] = 0;
            } //making two arrays and filling them with zeroes

            for (int i = 0; i<=leng-1; i++)
            {
                Console.Write(arrayone[i]);
            }
            Console.WriteLine(' '); //printing the first state of array


            for (int st=1; st<=16; st++) //my main loop
            {
                arraytwo[0]=0;
                arraytwo[leng - 1]=0; //making sure that first and last elements are zero. I'm not sure I need this since I fill both arrays with zeroes in the beginning. But it probably doesn't hurt?
                for (int i = 1; i<=leng-2; i++) //calculating new states for elements from second to second-to-last
                {
                    if (((arrayone[i-1]) + (arrayone[i]) + (arrayone[i+1]) == 0) | ((arrayone[i-1]) + (arrayone[i]) + (arrayone[i+1]) == 3) == true)
                        arraytwo[i] = 1; 
                    else 
                        arraytwo[i] = 0;
                }
                //by now arraytwo contains transformed version of arrayone

                for (int i = 0; i<=leng-1; i++)
                {
                    Console.Write(arraytwo[i]);

                } //printing result

                arrayone = arraytwo; //copying content of arraytwo to arrayone for the next round of transformation;
                Console.WriteLine(' '); 
            }



            Console.Write(" ");
            Console.ReadKey(true);
        }
    }
}

可调整版本:https ://dotnetfiddle.net/8htp9N

标签: c#arraysloops

解决方案


正如所指出的那样,您正在谈论一个对象并对其进行处理,最后您分配的是引用而不是值。一种对抗的方法是

对于您的线路:arrayone = arraytwo; 将其更改为:arrayone = (int[])arraytwo.Clone();

这将复制这些值——对于整数来说,这就足够了。


推荐阅读