问题描述
欢迎。我的问题是,我给了,我需要计算平均(这部分我做的)数字数组,但我必须要找到数组元素(模块),这是更接近平均水平。下面贴code(形式main()的规定)
Welcome. My problem is that I have given an array of numbers which I need to calculate the average (that part I did), but then I have to find the array element (module), which is closer to the average. Below paste the code (a form of main () imposed)
#include <iostream>
using namespace std;
double* aver(double* arr, size_t size, double& average){
double count;
for(int p = 0; p < size; p++)
count += arr[p];
count /= size;
double * pointer;
pointer = &count;
average = *pointer;
}
int main() {
double arr[] = {1,2,3,4,5,7};
size_t size = sizeof(arr)/sizeof(arr[0]);
double average = 0;
double* p = aver(arr,size,average);
cout << p << " " << average << endl;
}
该计划应该给结果
The program should give a result
4 3.66667
4 3.66667
我不知道如何检查哪些元素是最近到另一个,它代入* P
I have no idea how to check which element is nearest to another, and substitute it into *p
我将是任何帮助非常感激。
I will be very grateful for any help.
推荐答案
既然大家都在做的功课的孩子...
Since everybody is doing the kids homework...
#include <iostream>
using namespace std;
double min(double first, double second){
return first < second ? first : second;
}
double abs(double first){
return 0 < first ? first : -first;
}
double* aver(double* arr, size_t size, double& average){
double count;
for(int p = 0; p < size; p++)
count += arr[p];
average = count/size;
int closest_index = 0;
for(int p = 0; p < size; p++)
if( abs(arr[p] - average) <
abs(arr[closest_index] - average) )
closest_index = p;
return &arr[closest_index];
}
int main() {
double arr[] = {1,2,3,4,5,7};
size_t size = sizeof(arr)/sizeof(arr[0]);
double average = 0;
double* p = aver(arr,size,average);
cout << *p << " " << average << endl;
//Above ^^ gives the expected behavior,
//Without it you'll get nothing but random memory
}
我坚持认为你在p之前需要将*,它给该指针指向太值。无*则该值是存储器位置,这是在这种情况下,不确定的地址。问问你的教授/教师规格是否正确,因为它不是。
I insist that you need the * before the p, it gives the value that the pointer is pointing too. Without the * then the value is the address of the memory location, which is indeterminate in this case. Ask your professor/teacher whether the specification is correct, because it isn't.
尝试和了解所涉及的风格和功能 - 它并不复杂,写这样可以走很长的方式来使你的年级的工作更轻松。
Try and understand the style and functions involved - it isn't complicated, and writing like this can go a long ways to making your graders job easier.
另外该接口是非常漏水的,在实际工作中 - 考虑到一些标准库算法和容器,而不是
Also that interface is a very leaky one, in real work - consider some of the standard library algorithms and containers instead.
这篇关于检查该模块是最接近的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!