简体   繁体   English

查找与另一个给定数字最接近的数组数

[英]Finding the closest number of array to another given number

I have this program to write that I have a array of 11 numbers entered from me.我有这个程序要写,我有一个由我输入的 11 个数字的数组。 Then I need to find the avarage sum of those numbers, and then im asked to find the closest number of this array to the avarage sum, and then the most distant element of the array to the avarage sum again.然后我需要找到这些数字的平均和,然后我要求找到这个数组中最接近平均和的数字,然后再次找到数组中最远的元素到平均和。 SO far I manage to write a program to create this array and find the avarage sum.到目前为止,我设法编写了一个程序来创建这个数组并找到平均总和。 I asssume there is something to do with abs function of cmath libary , but so far I only fail to make it.我认为这与 cmath libary 的 abs 函数有关,但到目前为止我只是没能做到。

#include <iostream>


using namespace std;

int main() {


unsigned const int size = 11;
float number[size];

for (unsigned i = 0; i<size; i++) {
    cout << "Please enter value for number  "
        << i + 1 << ":";
    cin >> number[i];
}
for (unsigned i = 0; i<size; i++) {
    cout << "Number " << i + 1 << " is : "
        << number[i] << endl;
}
unsigned int sum = 0;
for (unsigned i = 0; i<size; i++) {
    sum += number[i];
}

What is the problem?问题是什么? You are not asking a question, just making a statement... It does seem that you have not posted the whole code..你不是在问问题,只是在发表声明......看来你没有发布整个代码......

In c++ usually to use "abs" you should use fabs from the "math.h" library!在 C++ 中,通常要使用“abs”,您应该使用“math.h”库中的 fabs!

You will be okay with the compare operators.您可以使用比较运算符。 Just traverse your array in a loop and calculate the difference between your compare value and the current value on your array.只需在循环中遍历数组并计算比较值与数组上的当前值之间的差异。 Initiate a temporary variable that keeps the array entry that created the smallest difference.启动一个临时变量,保留创建最小差异的数组条目。

Every time a difference that is smaller than the current one comes up replace the value in your temporary variable.每次出现小于当前差异的差异时,请替换临时变量中的值。

So you replace under the following condition: If |number[i] - average_value| < |tmp_closest_val -average_val| Then tmp_closest_val = number[i] EndIf因此,您在以下条件下进行替换: If |number[i] - average_value| < |tmp_closest_val -average_val| Then tmp_closest_val = number[i] EndIf If |number[i] - average_value| < |tmp_closest_val -average_val| Then tmp_closest_val = number[i] EndIf If |number[i] - average_value| < |tmp_closest_val -average_val| Then tmp_closest_val = number[i] EndIf . If |number[i] - average_value| < |tmp_closest_val -average_val| Then tmp_closest_val = number[i] EndIf

I hope you get the concept from that rough draft.我希望你从那个草稿中得到这个概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM