-2

可能重复:
我将如何为这个不变量编写一个循环?

以下 for 循环对于不变量是否正确?不变量:b[x] 是 b[h...s-1] 的最小值

 int x = h;      int h = s-1;

    // {inv: b[x] is the minimum of b[h...s-1]}
    while (s-1 != k) {
       s = s-1;
       if (b [s-1] < b[x])
          { x = s-1;}
    }
4

1 回答 1

2

如果你想找到一个数组的最小值,你可以这样做。

int b[] = {1,3,2,5,2,3};

//min needs to have a starting value so b[0] works fine.
int min = b[0];

//This loops over the remaining elements in the array. If it finds a value smaller than the current minimum, it reassigns min to that value.
for(int i = 1; i < b.length; i++)
{
     if(b[i] < min)
          min = b[i];
}

//If you haven't covered for loops yet, here is how you can do it with a while.
int i = 1;
while(i < b.length)
{
     if(b[i] < min)
          min = b[i];
     i++;
}

//b.length is just a way of getting the length of an array.
于 2012-04-18T04:14:55.840 回答