因此,我有一堆数组,并且尝试使用数组A与数组B的索引。因此,例如,如果我有Cucumber的名称,并且它在数组1中,则尝试将另一个数组中黄瓜的索引。 如下面的代码所示,最后一行代码不起作用,并告诉我我不能将double转换为int。 编辑,我将其更改为“ int index”,而现在的“ fmin(something1,something2)”也给了我同样的错误。
setState()
答案 0 :(得分:1)
最简单的解决方法是从函数中返回int
。
private int fmin(double[] a, int b)
{
double Min = a[0];
for (int i = 0; i < b; i++)
{
if (Min > a[i])
Min = a[i];
}
return Array.IndexOf(a, Min);
}
int index = fmin(something1, something2);
output = (something3[index]);
解决相同问题的另一种方法是在遍历数组时跟踪最小值的索引。
答案 1 :(得分:0)
fmin返回Min,它是double类型。然后,您要设置索引,将int类型输入为fmin(double)的返回值。使变量类型一致
答案 2 :(得分:0)
首先,作为一种好的做法,我建议您习惯于在开始每个算法时进行一些错误情况检查,以确保完全覆盖您的输入。
第二,正如 Eric Lippert 所说,您必须为变量分配有意义的名称,并避免在目的不同时重复使用它们,除非您过度-优化一些算法,这些算法会经常在大量迭代的循环中运行。
您还可以利用输出变量的强大功能:它们必须在函数返回之前设置。在异常情况下,该函数没有义务为输出变量设置任何值。所以你会有一个很好的函数,它从 minIndex
返回 minValue
和 arrayA
。
如果您需要一个从不抛出异常的“稳定”函数,我已经编写了另一个版本来实现“bool TryDoSomenthing(out result)
”模式。仅在索引计算成功的情况下,此函数才返回“true”。我在异常不理想的系统上广泛使用这种模式,因为它们在多个顺序故障的情况下会出现性能问题。
代码:
// Finds the index of the lowest value in the array, considering just the 'n' first numbers.
// Throws exceptions in case of bad input parameters.
private static void GetMin(double[] a, int n, out int minIndex, out double minValue)
{
if (a == null)
throw new ArgumentNullException(nameof(a));
if (a.Length <= 0)
throw new ArgumentException("array 'a' contains no elements");
if (n <= 0)
return new ArgumentException("'n' must be greater than 0");
minIndex = 0;
minValue = a[0];
if (n > a.Length)
n = a.Length;
for (i = 1; i < n; ++i)
if (minValue > a[i])
minValue = a[(minIndex = i)];
}
// Finds the index of the lowest value in the array, considering just the 'n' first numbers.
// Returns 'false' in case of bad input parameters.
private static bool TryGetMin(double[] a, int n, out int minIndex, out double minValue)
{
if (a == null || a.Length <= 0 || n <= 0)
{
minIndex = -1;
minValue = double.MinValue;
return false;
}
minIndex = 0;
minValue = a[0];
if (n > a.Length)
n = a.Length;
for (i = 1; i < n; ++i)
if (minValue > a[i])
minValue = a[(minIndex = i)];
return true;
}
internal static void Main()
{
double[] arrayA = new double[] { 3.0, 2.0, 4.0, 1.0 };
object[] arrayB = new object[] { 'x', 'y', 'z', 'w' };
int minIndex; // index of minimum value found in 'arrayA'
double minValue; // minimum value found in 'arrayA'
object b; // used for storing the element of arrayB at 'minIndex'
// With GetMin() - this code will throw an exception on bad inputs:
GetMin(arrayA, 3, out minIndex, out minValue);
b = arrayB[minIndex];
// Or with TryGetMin:
if(TryGetMin(arrayA, 3, out minIndex, out minValue))
{
b = arrayB[minIndex];
}
else
{
// TryGetMin() was not successful, do something about it.
b = null;
}
// Or simply:
b = TryGetMin(arrayA, 3, out minIndex, out minValue) ? arrayB[minIndex] : null;
//...
}