[英]how to assign a datacolumn value to a variable and use this variable in different method
[英]How to assign a new value from Method's Array to the Variable?
我的主要目标是创建一个方法,可以在其中输入一个数字,方法将从中选择一些其他数字(根据目的)并将它们组合在数组中。
我需要这个数组及其值是灵活的,所以我决定为Container()和Main()方法创建一个新变量,它位于 scope 内。 然后我将一个值从Container()分配给optainer ,但它不起作用( foreach不显示Container()的所有数字,只显示第一个)。 我的问题在哪里?
static int[] optainer;
static void Container()
{
uint numb = uint.Parse(Console.ReadLine());
for (int i = 1000000; i >= 1; i--)
{
if (numb % i == 0)
{
optainer = new int[] { i };
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Enter num. from 1 to 1 000 000");
Container();
foreach (int iw in optainer)
{
Console.WriteLine(iw);
}
// Expected: few numbers according to the condition; Real result: 1
```
你在 optainer 中总是只有一个元素,这一行是错误optainer = new int[] { i };
你总是创建一个只有一个项目的新数组,最后一个总是 1。
你可以这样改变
static List<int> optainer = new List<int>();
static void Main(string[] args)
{
Console.WriteLine("Enter num. from 1 to 1 000 000");
Container();
foreach (int iw in optainer)
{
Console.WriteLine(iw);
}
}
static void Container()
{
uint numb = uint.Parse(Console.ReadLine());
for (int i = 1000000; i >= 1; i--)
{
if (numb % i == 0)
{
optainer.Add(i);
}
}
}
我敢肯定有更性感的方式来做到这一点,但试试这个:
static void Container()
{
uint numb = uint.Parse(Console.ReadLine());
for (int i = 1000000; i >= 1; i--)
{
if (numb % i == 0)
{
int size = optainer.Length + 1;
Array.Resize(ref optainer, size);
optainer[size - 1] = i;
}
}
}
每次写
optainer = new int[] { i };
您创建一个新列表(覆盖旧列表),您必须将 append 添加到数组中。 因此,您需要知道数组的大小。 要保存 memory,您应该使用更动态的东西,例如列表。
以下是如何添加值的说明: Adding values to a C# array
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.