我有一个列表框,用户可以在其中输入十进制数字。假设他们将输入 5 个数字:
1.1
1.2
1.3
1.4
1.5
我需要得到这 5 个数字的所有变化的总和。例如 1.1 和 1.2
的总和,然后是 1.1 1.2 1.3
然后是 1.1 1.2 1.3 1.4
,然后是 1.2 1.4 1.5
然后1.1 1.3 1.5
。
我开始了一些事情,但经历了所有变化,一次只跳过一个数字:
List<Double[]> listNumber = new List<double[]>();
Double[] array;
for (int i = 0; i < listBox1.Items.Count; i++)
{
array = new Double[listBox1.Items.Count];
for (int k = 0; k < listBox1.Items.Count; k++)
{
if (!k.Equals(i))
{
array[k] = (Convert.ToDouble(listBox1.Items[k]));
}
}
listNumber.Add(array);
}
我需要找到一种方法来计算我想要的方式。
最佳答案
在您最初的尝试中,您的代码仅计算所有可能对的总和。从你的描述中,你还想找到三个数字的总和等等。
如果总是有 5 个小数,那么您可以简单地使用 5 个 for 循环。然而,更通用的设计会更干净
double[] input = double[5]; //Pretend the user has entered these
int[] counters = int[input.Length]; //One for each "dimension"
List<double> sums = new List<double>();
for (int i = 0; i < counters.Length; i++)
counters[i] = -1; //The -1 value allows the process to begin with sum of single digits, then pairs, etc..
while (true)
{
double thisSum = 0;
//Apply counters
for (int i = 0; i < counters.Length; i++)
{
if (counters[i] == -1) continue;
thisSum += input[counters[i]];
}
//Increment counters
counters[0]++; //Increment at base
for (int i = 0; i < counters.Length; i++)
{
if (counters[i] >= counters.Length)
{
if (i == counters.Length - 1) //Check if this is the last dimension
return sums; //Exhausted all possible combinations
counters[i] = 0;
counters[i+1]++;
}
else
break;
}
}
这里没有任何代码来避免两次添加相同的数字(我会让你尝试完成它。提示:你可以在包含“增量计数器”的增量计数器部分之后简单地这样做部分和 while 循环内的新“检查计数器”部分,当计数器是唯一的时打破 while 循环...
注意:我还没有测试过这段代码,但它会很接近,并且可能会有一两个错误 - 如果您需要任何关于这些错误的帮助,请告诉我。
关于c# - 在 C# 中计算(复杂的)十进制数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14034898/