排序值接近零并打印其位置 [英] Sorting value closer to zero and print their locations
问题描述
我有一个float数据类型的数组。 ARR = [ - 0.05,0.03,0.09,0.1];现在我已经编写了代码,以便它将最接近的值显示为零及其位置。
但现在我需要这样做,以便所有数组值都应该接近零。
如果数组索引从零开始。
输出应该像
1. 0.03 location = 1
2. -0.05位置= 0
3. 0.09位置= 2
4. 0.1位置= 3
我的尝试:
i have an array of float datatype. arr=[-0.05,0.03,0.09,0.1]; now i have written code such that it will display the closest value to zero and their location.
but now i need to do in such a way that all the array values should be in an order closer to zero.
if array index starting from zero.
the output should be like
1. 0.03 location=1
2. -0.05 location=0
3. 0.09 location=2
4. 0.1 location=3
What I have tried:
#include<stdio.h>
int main()
{
float array[100], minimum;
int size, c, location = 1;
printf("Enter the number of elements in array\n");
scanf("%d",&size);
printf("Enter %d integers\n", size);
for ( c = 0 ; c < size ; c++ )
scanf("%f", &array[c]);
minimum = array[0];
for ( c = 0 ; c < size ; c++ )
{
if(array[c]<0 && minimum<0)
{
if ( (-array[c]) < (-minimum ) )
{
minimum = array[c];
location = c+1;
}
}
else if(array[c]<0 && minimum>0)
{
if ( (-array[c]) < (minimum ) )
{
minimum = array[c];
location = c+1;
}
}
else if(array[c]>0 && minimum<0)
{
if ( (array[c]) < (-minimum ) )
{
minimum = array[c];
location = c+1;
}
}
else{
if ( array[c] < minimum )
{
minimum = array[c];
location = c+1;
}}
}
printf("Minimum element is present at location %d and it's value is %f.\n", location, minimum);
return 0;
}
推荐答案
使用 qsort [ ^ ]用于此目的的函数。
Use the qsort[^] function for the purpose.
您必须对数组进行排序。因为你需要在排序后打印出初始位置,你也必须存储它。解决方案是使用以下结构:
You have to sort the array. Because you need to print out the initial position after sorting you have to store that too. The solution is to use a structure:
typedef struct
{
int position;
float value;
} val_struct;
int main()
{
val_struct array[100];
/* ... */
for ( c = 0 ; c < size ; c++ )
{
array[c].position = c;
scanf("%f", &array[c].value);
}
/* ... */
}
现在对数组进行排序并根据需要打印所有项目。因为这似乎是某种功课,所以不会发布最终的解决方案。您可以在线搜索排序算法或使用 qsort - C ++参考a> [ ^ ]。
这篇关于排序值接近零并打印其位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!