[英]Find closest number C++ using arrays, floats
我需要找到与给定数字中的平均值最接近(和次要)的数字。 例如:
如果给定数字为1,2,3,4,5,则平均值将为3,最接近的数字为2和4,但次要数字为2,因此结果应为2。
或者,如果给定的数字为1、325、350、299,则平均值为243.75,因此最接近的数字为299。
int best = a[0];
for (i = 1; i < count; ++i)
best = abs(a[i] - x) < abs(best - x) ? a[i] : best;
您的代码几乎是正确的...您只需要检查与平均x
的距离是否与最佳距离相同 ,但是在次要方面,而best
距离则不是。
double i_delta = abs(a[i] - x);
double x_delta = abs(best - x);
if (i_delta < x_delta)
best = a[i];
else if (i_delta == x_delta && a[i] < best)
best = a[i];
(您必须对这些值进行一次遍历以计算平均值,因此您的总体算法将为O(n)。因此,像您正在使用的额外迭代不会降低总体big-O效率...全部好。)
这并不困难,您应该能够做到。 我假设这是您学校作业中的问题,并且您没有心情
int closest(int* array, int size){
//Calculating sum for finding average first
double sum = 0.0;
for (int i=0; i< size; i++){
sum+= array[i]*1.0;
}
//Here is our average
double average = sum/size;
//Assuming initial answer is very huge so that every other comparison is less than this
int answer = 100000000;
for (int i=0; i< size; i++){
//Finiding the difference for current element
double temp = abs(array[i]-average);
double temp1 = abs(answer - average);
//If current difference is less than previous one that replace the previous answer
if (temp < temp1) answer = array[i];
//If they are equal then accept the minor one
else if (temp == temp1){
if (array[i]< answer) answer = array[i];
}
}
return answer;
}
PS:在这里问这样的问题不是一个好习惯。 您应该先尝试过,然后再尝试发布问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.