[英]How to find the closest elements of average in C?
Hi , how can I find the closest number of average in this array?嗨,我怎样才能找到这个数组中最接近的平均值? Idk how to do this.
我知道如何做到这一点。
#include<stdio.h>
#include<stdlib.h>
int arraysum();
int main()
{
int n, A[100], i, b, sum;
float average;
printf("Enter number of elements in array: ");
scanf("%d", &n);
printf("\nEnter %d numbers: ", n);
for(i=0; i<n; i++)
scanf("%d", &A[i]);
printf("Numbers of this array: ");
for(i=0; i<n; i++)
printf("%d ", A[i]);
average=arraysum(A, sum, i, n)/n;
printf("\nAverage is: %.2f", average);
}
int arraysum(int A[], int sum, int i, int n)
{
sum=0;
for(i=0; i<n; i++)
sum+=A[i];
return sum;
}
Thanks in advance, guys!提前致谢,伙计们! :D
:D
After finding the average, iterate looking for closest.找到平均值后,迭代寻找最接近的。
// Pseudo code
average=arraysum(A, sum, i, n)/n;
best = element 0
for (each element in the array [1...n-1])
if (|A[i] - average| < |A[best] - average|)
best = i
To cope with an average than is not exactly an integer and not use unnecessary floating point math ...为了处理不完全是整数的平均值并且不使用不必要的浮点数学......
long long scaled_average = arraysum(A, sum, i, n);
best = element 0
for (each element in the array [1...n-1])
if (|n*A[i] - scaled_average| < |n*A[best] - scaled_average|)
best = i
Consider using long long
for sum
to avoid overflow.考虑对
sum
使用long long
以避免溢出。
Code simplification: no need to pass in sum
.代码简化:无需传入
sum
。
long long arraysum(int A[], int i, int n) {
long long sum = 0;
for(i=0; i<n; i++)
sum+=A[i];
return sum;
}
First suggestion is to move the declaration of A[100];
第一个建议是移动
A[100];
的声明A[100];
from here从这里
int n, A[100], i, b, sum;
To just after the scanf()
statement, to create a VLA :在
scanf()
语句之后,创建一个VLA :
int n, i, b, sum;
...
printf("Enter number of elements in array: ");
scanf("%d", &n);
int A[n];
for(i=0; i<n; i++)
scanf("%d", &A[i]);
...creating an array just the right size for the need. ...根据需要创建一个大小合适的数组。
Once the array is populated, loop through it and use comparison operators to find the closest to the difference of array values and average .一旦数组被填充,循环遍历它并使用比较运算符来找到最接近数组值和平均值的差异。 (pseudo code:
fabs(a[i]-ave) < fabs(a[i+1]-ave)
) tracking the array index of the array values closest. (伪代码:
fabs(a[i]-ave) < fabs(a[i+1]-ave)
)跟踪最接近的数组值的数组索引。
Example:例子:
average = arraysum(A, sum, i, n)/(n*(1.0));//divide by floating point
int closestIndex;
findClosest(int A, 100, average, &closestIndex);
printf("Index of value closest to %f is %d\nClosest value is: %d\n",
average, closestIndex, A[closestIndex]);
Where findClosest()
is defined:定义
findClosest()
的地方:
void findClosest(int A[], size_t size, double ave int *index)
{
int smallestIndex;
for(int i=0;i<size-1;i++)
{
smallestIndex = fabs((double)A[i]-ave) < fabs((double)A[i+1]-ave) ? i : i + 1;
}
*index = smallestIndex
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.