将数组的元素相互比较

时间:2012-03-06 21:48:26

标签: c arrays

for (x=1; x<=4; x++){
    slope = ((x+1)-(x))/(a[x+1] - a[x]);
    printf("Slope: %d \n", slope);
}

所以,是的。这是一个家庭作业问题。我试图将数组a = {1, 2, 3, 4}的每个元素与其他每个元素进行比较并找到斜率。 x是值,y是索引。这样做吗?难道不会有16个斜坡吗?

2 个答案:

答案 0 :(得分:3)

提示:

C中的数组是从零开始的。你从[1]循环到[4]并且应该从[0]循环到[3]。您的代码将导致数组越界错误。

查看嵌套循环。

答案 1 :(得分:2)

要将数组的每个元素与每个其他元素进行比较,您需要2个嵌套循环。假设数组A的长度为n,要将每个元素与每个其他元素进行比较,请执行以下操作:

int A[] = {0, 1, 2, 3};
unsigned int n=sizeof(A)/sizeof(int);
int i,j;
for(i = 0; i < n; i++)
{
  for(j = 0; j < n; j++)
  {
    if(i != j)
      printf("Slope is %d\n",(i-j)/(A[i]-A[j]);
  }
}

输出:

Slope is 1
Slope is 1
Slope is 1
Slope is 1
Slope is 1
Slope is 1
Slope is 1
Slope is 1
Slope is 1
Slope is 1
Slope is 1
Slope is 1

if(i != j)的原因是因为您无法计算2个相同点之间的斜率,这发生在i==j时。

此外,如上所述,数组为0-indexed,这意味着您应该访问从A[0]A[n-1]的元素,如上面的循环所示。