c# - 为什么我的 C# 代码不能按预期工作(数组转换,新手)
问题描述
我正在尝试获取数字数组(仅限 0 或 1)并反复对其进行转换,如下所示:
- 第一个和最后一个数字始终为 0;
- 所有其他数字都来自数组的先前状态:如果数组 [n] 及其两个邻居(数组 [n-1]、数组 [n] 和数组 [n+1])具有相同的值(三个 0 或三个1s) 那么 newarray[n] 应该是 1,否则它应该是 0(产生漂亮的模式)。
例如,如果数组大小为 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);
}
}
}
解决方案
正如所指出的那样,您正在谈论一个对象并对其进行处理,最后您分配的是引用而不是值。一种对抗的方法是
对于您的线路:arrayone = arraytwo;
将其更改为:arrayone = (int[])arraytwo.Clone();
这将复制这些值——对于整数来说,这就足够了。
推荐阅读
- javascript - AngularJS 调用 WebMethod 并返回一个 JSON 字符串
- php - laravel 获取所有具有关系数组的模型
- javascript - 为什么我的 Plotly 图表上没有加载数据?
- bash - 循环通过制表符分隔的文件
- python - 如何在 Python 中设置 Basemap 的偏移量?
- c# - 为什么我不能通过 C# 使用 R 绘制图形?
- javascript - 客户端如何阻止JS代码执行?
- haskell - 用数据类型中的函数推导 (Show, Eq)
- java - JNI 本机接口和 JavaFX - NoClassDefFoundError
- sql - 在存储过程中接收多个结果集