我需要一些帮助来制作一个函数,该函数可以根据
对 2 个数组进行排序1 - 求值:ratio = array1[]/array2[]
2 - 对结果进行排序并根据我们得到的结果对 2 个数组进行排序
3 - 使更改发生在我放入参数的数组上
这就是我尝试这样做的方式,但出现错误:
||=== Build: Debug in test (compiler: GNU GCC Compiler) ===|
C:\Users\Amine\Desktop\Knapsack\test\main.c||In function 'main':|
C:\Users\Amine\Desktop\Knapsack\test\main.c|40|warning: passing argument 1 of 'triVariable' from incompatible pointer type [-Wincompatible-pointer-types]|
C:\Users\Amine\Desktop\Knapsack\test\main.c|7|note: expected 'int **' but argument is of type 'int (*)[4]'|
C:\Users\Amine\Desktop\Knapsack\test\main.c|40|warning: passing argument 2 of 'triVariable' from incompatible pointer type [-Wincompatible-pointer-types]|
C:\Users\Amine\Desktop\Knapsack\test\main.c|7|note: expected 'int **' but argument is of type 'int (*)[4]'|
||=== Build finished: 0 error(s), 2 warning(s) (0 minute(s), 0 second(s)) ===|
||=== Run: Debug in test (compiler: GNU GCC Compiler) ===|
我似乎找不到解决办法。
void triVariable(int **a, int **c, int n){
int i, j, temp, tempa, tempc;
int *ratio = malloc(n*sizeof(int));
for(i=0;i<n;i++){
ratio[i]= (*c)[i] / (*a)[i];
}
for(i=0; i<n; i++) {
for(j=i+1;j<n; j++) {
if(ratio[j]<ratio[i]) {
temp=ratio[i];
ratio[i]= ratio[j];
ratio[j]= temp;
tempa=(*a)[i];
(*a)[i]=(*a)[j];
(*a)[j]=tempa;
tempc=(*c)[i];
(*c)[i]=(*c)[j];
(*c)[j]=tempc;
}
}
}
}
int main(){
int n=5;
int c[]={12,8,2,5};
int a[]={5,4,1,3};
triVariable(&a, &c, n);
printf("C : ( ");
for(int i=0;i<4;i++){
printf("%d ", c[i]);
}
printf(")\n");
printf("A : ( ");
for(int i=0;i<4;i++){
printf("%d ", a[i]);
}
printf(")\n");
}
如果有人能指出我遗漏的东西,那就太好了!
最佳答案
感谢@someprogrammerdude 我设法更正了我的代码!
void triVariable(int *a, int *c, int n){
int i, j, temp, tempa, tempc;
int ratio[n];
for(i=0;i<n;i++){
ratio[i]= (c)[i] / (a)[i];
}
for(i=0; i<n; i++) { //On met à jour notre liste d'objets pour qu'elle soit trier du plus grand ratio au plus petit
for(j=i+1;j<n; j++) {
if(ratio[j]<ratio[i]) {
temp=ratio[i];
ratio[i]= ratio[j];
ratio[j]= temp;
tempa=(a)[i];
(a)[i]=(a)[j];
(a)[j]=tempa;
tempc=(c)[i];
(c)[i]=(c)[j];
(c)[j]=tempc;
}
}
}
free(ratio);
}
int main(){
int n=4;
int c[]={12,8,2,5};
int a[]={5,4,1,3};
triVariable(&a[0], &c[0], n);
printf("C : ( ");
for(int i=0;i<n;i++){
printf("%d ", c[i]);
}
printf(")\n");
printf("A : ( ");
for(int i=0;i<n;i++){
printf("%d ", a[i]);
}
printf(")\n");
}
关于c - 使用它们的比率对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48972983/