(指针与一维数值数组)写函数,它将数组b中大于等于x的数顺序复制到数组a中,其中n为两个数组的大小。请分别用数组写法和指针写法完成上述功能。
函数原型分别为分别为select1(double a[], double b[], int n, double x)和select2(double *a, double *b, int n, double x)。
两种方法基础思路是,输入数组b,将b中数组与x比较并复制到a数组中,最后a数组排序并输出a。
void select1(double a[], double b[], int n, double x);
void select2(double* a, double* b, int n, double x);
int main()
{
//数组法
double a[12] = {0};
double b[12] = { 0 };
int i = 0;
double x = 0;
printf("请输入数组:");
while (scanf_s("%lf", &b[i]) == 1)//这里需要输入一个非法字符打破,比如输入x
{
i++;
}
getchar();
printf("请输入界定值x:");
scanf_s("%lf", &x);
select1(a,b,12,x);
//指针法
double arr[12] = { 0 };
double brr[12] = { 0 };
double* a = arr;
double* b = brr;
int j = 0;
double x = 0;
printf("请输入数组:");
while (scanf_s("%lf", b + j) == 1)//同理如上
{
j++;
}
getchar();
printf("请输入界定值x:");
scanf_s("%lf", &x);
select2(a, b, 12, x);
return 0;
}
void select1(double a[], double b[], int n, double x)
{
int m = -1;
double t = 0;
for (int j = 0; j < 12; j++)
{
if (b[j] >= x)
{
m++;
a[m] = b[j];
}
}
for (int i = 0; i < m; i++)
{
for (int q = 0; q < m-i; q++)
{
if (a[q] > a[q + 1])
{
t = a[q];
a[q] = a[q + 1];
a[q + 1] = t;
}
}
}
for (int w = 0; w <= m; w++)
{
printf("%.0lf ", a[w]);
}
}
void select2(double* a, double* b, int n, double x)
{
int m = -1;
double t = 0;
for (int j = 0; j < 12; j++)
{
if (*(b + j) >= x)
{
m++;
*(a + m) = *(b + j);
}
}
for (int i = 0; i < m; i++)
{
for (int q = 0; q < m - i; q++)
{
if (*(a + q) > *(a + q + 1))
{
t = *(a + q);
*(a + q) = *(a + q + 1);
*(a + q + 1) = t;
}
}
}
for (int w = 0; w <= m; w++)
{
printf("%.1lf ", *(a + w));
}
}
该代码可以进行数据调整,比如数组长度,输入方式等等。