我有两个双打数组。例如:{1,2,3} {4,5,6}例如,我们使用(x,y)坐标为(1,4),(2,5)和(3,6)。因此,此示例中有3个数据点。我们需要计算所有点之间的斜率,并将斜率存储为最大绝对值。为此,我在'for'循环中有一个带'for'循环的函数。当我在Main中使用它时,我的代码成功计算出最大绝对值斜率。
所以现在最后一步是在第一个数组中存储这个最大斜率出现的位置,并打印出第二个数组中相同位置的值。
注意:我的代码在应该的位置之前将值打印出一个位置。例如,如果最大斜率出现在第4和第5位置,那么我的代码将打印出第3和第4个位置。
using System;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
List<double> Array1 = new List<double>();
List<double> Array2 = new List<double>();
Array1.Add(Convert.ToDouble(columns[0]));
Array2.Add(Convert.ToDouble(columns[1]));
int[] positions = GreatestSlopeLocation(Array1, Array2);
Console.WriteLine("The Location of the max slope is {0} {1}",
Array2[positions[0]], Array2[positions[1]]);
}
static int[] GreatestSlopeLocation(List<double> x, List<double> y)
{
int size = x.Count;
double maxSlope = Double.MinValue; // don't set this to 0
// consider case when all slopes are negative
//
int index1 = 0;
int index2 = 0;
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
double slope = (y[j] - y[i]) / (x[j] - x[i]);
if (slope > maxSlope) // I think you want > instead of < here
{
maxSlope = slope;
index1 = i;
index2 = j;
}
}
}
return new int[]{index1, index2};
}
}
答案 0 :(得分:5)
如果我理解正确,您当前的代码将始终以i == size - 2, j==size - 1
结束...因为每个斜率都大于double.MinValue
,这是maxSlope
的唯一值{1}}永远都需要。
问题在于:
if (slope > maxSlope)
{
slope = maxSlope;
index1 = i;
index2 = j;
}
如果您找到了新的最大斜率,则记住它的索引......但不记得斜率本身。您正在为slope
变量分配一个新值,该变量在该迭代中永远不会再次使用。您想要记住maxSlope
中的新最大斜率:
maxSlope = slope;