|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#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;
}
现在,当你运行程序时,它应该能够正确地删除最小值并输出数组中剩余的元素。
|
|