我想写一个程序来计算每个数字和这个数组的相同数字之间的最长距离这是我的代码
int max_dist = 0;
for (int j= 0; j < n; j++)
{
for (int secondelement = 1; secondelement <= n;secondelement++)
{
int first = array[j];
int second = array[secondelement];
secondelement++;
if (first == second)
{
max_dist = max_dist +1;
System.Console.WriteLine(first+""+max_dist);
first = second;
break;
}
else
{
break;
}
}
}
但是缺少一些东西,我不知道这是什么,因为我的程序打印了错误的值..有什么问题,哪里出了问题
for example if my array is
2 3 5 7 3
out put is
3 3
2 7 5 7 3 4 5 6 7
out put is
7 4
1 3 5 7 1
out put is
1 3
它的平均数 x 最长距离是 y 再次出现注意:数字可能会找到很多次
你的第一个错误是你增加了循环中的第二个元素。第二个错误是你增加了 max_dist 而不是计算索引之间的差异。在第二个循环的每次迭代中先计算也是没有意义的,您应该从第一个循环的当前索引的下一个开始内部循环。跳出循环也是没有意义的。
编辑:
让我们修复您的代码:
for (int j= 0; j < n; j++)
{
int max_dist = 0;
int first = array[j];
for (int secondelement = j + 1; secondelement < n;secondelement++)
{
int second = array[secondelement];
if (first == second)
{
if (max_dist < secondelement - j)
{
max_dist = secondelement - j;
}
first = second;
}
}
System.Console.WriteLine(first+" "+max_dist);
}
编辑:
您还需要避免重复输出:
for (int j= 0; j < n; j++)
{
int max_dist = 0;
int first = array[j];
int earlierIndex = -1;
for (int k = 0; (earlierIndex < 0) && (k < j); k++) {
if (first == array[k]) {
earlierIndex = k;
}
}
if (earlierIndex >= 0) continue;
for (int secondelement = j + 1; secondelement < n;secondelement++)
{
int second = array[secondelement];
if (first == second)
{
if (max_dist < secondelement - j)
{
max_dist = secondelement - j;
}
first = second;
}
}
System.Console.WriteLine(first+" "+max_dist);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句