【发布时间】:2017-07-04 09:36:17
【问题描述】:
我从以下链接获得了 c 代码
How to get the indices of top N values of an array?
我在上面的链接代码中添加了输入激励部分,开发了下面的c-model
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main() {
double *arr =malloc(sizeof(double)*10);
int N=10;
int n =5;
int *top =malloc(sizeof(int)*10);
arr[0] = 0.00623;
arr[1] = 0.745;
arr[2] = 0.440;
arr[3] = 0.145;
arr[4] = 0.645;
arr[5] = 0.741;
arr[6] = 0.542;
arr[7] = 0.445;
arr[8] = 0.146;
arr[9] = 0.095;
top[0] = 100;
top[1] = 100;
top[2] = 100;
top[3] = 100;
top[4] = 100;
int top_count = 0;
int i;
for (i=0;i<N;++i) {
// invariant: arr[top[0]] >= arr[top[1]] >= .... >= arr[top[top_count-1]]
// are the indices of the top_count larger values in arr[0],...,arr[i-1]
// top_count = max(i,n);
int k;
for (k=top_count;k>0 && arr[i]>arr[top[k-1]];k--){
}
// i should be inserted in position k
if (k>=n) continue; // element arr[i] is not in the top n
// shift elements from k to top_count
int j=top_count;
if (j>n-1) { // top array is already full
j=n-1;
} else { // increase top array
top_count++;
}
for (;j>k;j--) {
top[j]=top[j-1];
}
// insert i
top[k] = i;
printf("top[%0d] = %0d\n",k,top[k]);
}
return top_count;
}
执行代码后,我得到以下输出
top[0] = 0
top[0] = 1
top[1] = 2
top[2] = 3
top[1] = 4
top[1] = 5
top[3] = 6
top[4] = 7
top[2] 的索引错误。应该是top[2] =4。我无法解码为什么它只给top[2] 带来问题?
【问题讨论】:
-
我建议您考虑如何实现您想要实现的目标,并在此基础上检查程序是否正在执行您想要的操作。复制一些你看不懂的代码对你学习没有帮助...
-
除了 Betlista 的评论之外,学习使用调试器并在变量在程序中发生变化时检查它们的内容对您很有帮助。
-
附带说明,如果您要从代码中初始化数组,最好将其设为普通数组而不是堆分配(即
const double arr[] = { 0.00623, 0.745, ... };)。 -
如果只想获取 5 个值,为什么还需要大小为 10 的索引数组?
-
main的返回值是对操作系统的程序状态的指示,0表示正常,其他任何值表示发生了一些错误......