请问为啥在main函数里面接收不到DeleteMin函数的返回值
#include <stdio.h>#include <stdlib.h>
int DeleteMin(int **p, int n)
{
if(!n)
{
printf("error!\n");
exit(1);
}
int temp,t;
int *q;
q = *p;
temp = *q;
for(int i = 0; i < n-1; i++)
{
if(*(q+i) < temp)
{
temp = *(q+i);
t = i;
}
}
*(q+t) = *(q+n-1);
return temp;
}
int main(void)
{
int n,min;
printf("How many pieces of data you want to enter:");
scanf("%d", &n);
int *arr = (int *)malloc(n * sizeof(int));
for(int i = 0; i < n; i++)
{
printf("Please enter the %d number:", i+1);
scanf("%d", arr+i);
}
min = DeleteMin(&arr, n);
for(int j = 0; j < n-1; j++)
{
printf("arr[%d]=%d\n", j, *(arr+j));
}
printf("Min = %d\n", min);
return 0;
}
输出结果如下:
How many pieces of data you want to enter:4
Please enter the 1 number:1
Please enter the 2 number:2
Please enter the 3 number:3
Please enter the 4 number:4(后面就没了,自动结束了)QWQ 求顺序表中的最小值,删除并打印最小值,空出来的元素位置用最后一个元素来代替。
你的程序中的错误是在DeleteMin函数中未能正确地删除最小值。问题出在DeleteMin函数中的for循环。你需要初始化t为0,以便在循环之后能够正确地删除最小值。以下是修复后的代码:
#include <stdio.h>
#include <stdlib.h>
int DeleteMin(int **p, int n)
{
if(!n)
{
printf("error!\n");
exit(1);
}
int temp,t = 0; // 初始化t为0
int *q;
q = *p;
temp = *q;
for(int i = 0; i < n-1; i++)
{
if(*(q+i) < temp)
{
temp = *(q+i);
t = i;
}
}
*(q+t) = *(q+n-1);
return temp;
}
int main(void)
{
int n,min;
printf("How many pieces of data you want to enter:");
scanf("%d", &n);
int *arr = (int *)malloc(n * sizeof(int));
for(int i = 0; i < n; i++)
{
printf("Please enter the %d number:", i+1);
scanf("%d", arr+i);
}
min = DeleteMin(&arr, n);
for(int j = 0; j < n-1; j++)
{
printf("arr[%d]=%d\n", j, *(arr+j));
}
printf("Min = %d\n", min);
return 0;
}
现在,当你运行程序时,它应该能够正确地删除最小值并输出数组中剩余的元素。 懂了懂了,谢谢大佬{:9_228:} isdkz 发表于 2023-3-24 14:12
你的程序中的错误是在DeleteMin函数中未能正确地删除最小值。问题出在DeleteMin函数中的for循环。你需要初 ...
懂了,谢谢大佬{:9_228:}
页:
[1]