I filled an array with 30 random numbers and calculated average. I want to display how many numbers are higher than the average. I tried making a function "aboveAverage" and check if the numbers are higher than the average and than just increase the count "num_over_average++". The problem is I don't know how to pass a value "avg" from function to another function.
#include <iostream>
#include <ctime>
using namespace std;
const int n = 30;
void fillArray(int age[], int n) {
srand(time(NULL));
for (int index = 0; index < n; index++) {
age[index] = (rand() % 81) + 8;
}
}
void printArray(int age[], int n) {
for (int index = 0; index < n; index++) {
cout << age[index] << endl;
}
}
double printAverage(int age[], int n) {
double sum;
double avg = 0.0;
for (int i = 0; i < n; i++) {
sum = sum + age[i];
}
avg = ((double) sum) / n;
cout << avg << endl;
return avg;
}
void aboveAverage(int age[], int n) {
double avg;
int num_over_average = 0;
for(int i = 0; i < n; i++){
if(age[i] > avg) {
num_over_average++;
}
}
cout<<num_over_average;
}
int main(int argc, char *argv[]) {
int age[n];
fillArray(age, n);
cout << "array: " << endl;
printArray(age, n);
cout << endl;
aboveAverage(age, n);
//example: Days above average: 16
}
This should be a comment, but I don't have enough reps :(
Change aboveAverage to void aboveAverage(int age[], int n, double avg)
Return avg from printAverage function
Change the last part of your main code to
double avg;
avg = printAverage(age, n);
aboveAverage(age, n, avg);
Hope this helps!
You have two solutions using your code:
Either you call printAverage() to initialise avg in aboveAverage() :
void aboveAverage(int age[], int n) {
double avg = printAverage();
...
}
Or you pass the average at parameter of aboveAverage() after having computed it with printAverage() :
void aboveAverage(int age[], int n, double avg) {
...
}
If you use the standard library you can do that with two lines of code:
double average = std::accumulate(std::begin(age), std::end(age), 0.0) / std::size(age);
int above_average = std::count_if(std::begin(age), std::end(age),
[average](double value) { return average < value; });
Okay, you might count that as three lines.
One major advantage of this approach over the code in the question is that you can change the container type to, say, vector<double> without having to change any of this code.
Well is pretty simple but dependent on your situation, I'll elaborate.
I'm the case when it's part of a bigger function (do-somthing())
You could calculate the average value like so and pass it to your "aboveAverage" function and print it:
double n_average = printAverage(nArr_ages, n_agesArraySize);
aboveAverage(nArr_ages, n_agesArraySize, n_averag);
Myself would probably rewrite the printAverage function as two functions, one that returns the average value based on the array and another that prints it not both at once because it violates the SOLID principals of a single responsibility and that a function name should reflect exactly what it does, in this case maybe calculateAverage or getAverageAge or any other appropriate name will do (try and name your functions like the english language so your code will be read like a song.
For example:
const size_t n = 30;
double calculateAverage(int nArr_ages[], int n_agesArraySize) {
double sum = 0.0;
double avg = 0.0;
for (int indexInArray = 0; indexInArray < n_agesArraySize; indexInArray++) {
sum = sum + age[indexInArray];
}
average = ((double) sum) / n_agesArraySize;
return average;
}
int aboveAverageCells(int ages[], int n_agesArraySize ) {
double average = calculateAverage(ages, n);
int num_over_average = 0;
for(int indexInArray = 0; indexInArray < n_agesArraySize; indexInArray++) {
if(ages[indexInArray] > avg) {
num_over_average++;
}
}
return num_over_average;
}
Now just call them in order, save the returned values to local variables in the main function and print using cout also locally in main.
As a side note next time maybe choose different names for the const and the local functions variable for the array size.
Related
I have created a program that prompts a user to enter a data set. The program stores and sorts the data, then computes a variance and the standard deviation of the array. However, I am not getting the correct computations for variance and standard deviation (the answer is slightly off). Anyone know what the issue seems to be?
#include <iostream>
#include <iomanip>
#include <array>
using namespace std;
//function declarations
void GetData(double vals[], int& valCount);
void Sort(double vals[], int& valCount);
void printSort(double vals[], int& valCount);
double Variance(double vals[], int valCount);
double StandardDev(double vals[], int valCount);
double SqRoot(double value); //use for StandardDev function
//function definitions
int main ()
{
double vals = 0;
int valCount = 0; //number of values to be processed
//ask user how many values
cout << "Enter the number of values (0 - 100) to be processed: ";
cin >> valCount;
//process and store input values
GetData(&vals, valCount);
//sort values
Sort(&vals, valCount);
//print sort
cout << "\nValues in Sorted Order: " << endl;
printSort(&vals, valCount);
//print variance
cout << "\nThe variance for the input value list is: " << Variance(&vals, valCount);
//print standard deviation
cout << "\nThe standard deviation for the input list is: " <<StandardDev(&vals, valCount)<< endl;
return 0;
}
//prompt user to get data
void GetData(double vals[], int& valCount)
{
for(int i = 0; i < valCount; i++)
{
cout << "Enter a value: ";
cin >> vals[i];
}
}
//bubble sort values
void Sort(double vals[], int& valCount)
{
for (int i=(valCount-1); i>0; i--)
for (int j=0; j<i; j++)
if (vals[j] > vals[j+1])
swap (vals[j], vals[j+1]);
}
//print sorted values
void printSort(double vals[], int& valCount)
{
for (int i=0; i < valCount; i++)
cout << vals[i] << "\n";
}
//compute variance
double Variance(double vals[], int valCount)
{
//mean
int sum = 0;
double mean = 0;
for (int i = 0; i < valCount; i++)
sum += vals[i];
mean = sum / valCount;
//variance
double squaredDifference = 0;
for (int i = 0; i < valCount; i++)
squaredDifference += (vals[i] - mean) * (vals[i] - mean);
return squaredDifference / valCount;
}
//compute standard deviation
double StandardDev(double vals[], int valCount)
{
double stDev;
stDev = SqRoot(Variance(vals, valCount));
return stDev;
}
//compute square root
double SqRoot(double value)
{
double n = 0.00001;
double s = value;
while ((s - value / s) > n)
{
s = (s + value / s) / 2;
}
return s;
}
There was quite a bit wrong with the code that was causing your errors. Type mismatches, but more importantly, you never created an array to store the values. You treated a plain double like an array and got lucky your program never crashed on you.
Below is a working version of your code, verified with a made up data set and Excel. I left as much of your code there as possible, just commented out when appropriate. If I commented it out, I didn't make any changes to it, so there may still be errors.
Vector over array in this case. You don't know the size up front (at compile time), and vectors are easier than dynamic arrays. You also never had an array. Vectors also know how big they are, so you don't need to pass the size around.
Type mismatches. Your functions keep expecting an array of doubles, but your sum was an int, among many other mismatches. You were also passing a plain double like it was an array, writing in memory that wasn't yours to change like that.
Best practices to start now. Stop with using namespace std;. Just qualify your names when needed, or be more specific with lines like using std::cout; at the top of a function. Your naming was all over the place. Pick a naming scheme and stick with it. Names starting with a capital letter are generally reserved for classes or types.
#include <iomanip>
#include <iostream>
// #include <array> // You never actually declared a std::array
#include <vector> // You don't know the size ahead of time, vectors are the
// right tool for that job.
// Use what's available
#include <algorithm> // std::sort()
#include <cmath> // std::sqrt()
#include <numeric> // std::accumulate()
// function declarations
// Commented out redundant functions, and changed arguments to match
void get_data(std::vector<double>& vals);
// void Sort(double vals[], int& valCount);
void print(const std::vector<double>& vals);
double variance(const std::vector<double>& vals);
double standard_dev(const std::vector<double>& vals);
// double SqRoot(double value); //use for StandardDev function
// function definitions
int main() {
int valCount = 0; // number of values to be processed
// ask user how many values
std::cout << "Enter the number of values (0 - 100) to be processed: ";
std::cin >> valCount;
std::vector<double> vals(valCount, 0);
// Was just a double, but you pass it around like it's an array. That's
// really bad. Either allocate the array on the heap, or use a vector.
// Moved to after getting the count so I could declare the vector with
// that size up front instead of reserving later; personal preference.
// process and store input values
get_data(vals);
// sort values
// Sort(&vals, valCount);
std::sort(vals.begin(), vals.end(), std::less<double>());
// The third argument can be omitted as it's the default behavior, but
// I prefer being explicit. If compiling with C++17, the <double> can
// also be omitted due to a feature called CTAD
// print sort
std::cout << "\nValues in Sorted Order: " << '\n';
print(vals);
// print variance
std::cout << "\nThe variance for the input value list is: " << variance(vals);
// print standard deviation
std::cout << "\nThe standard deviation for the input list is: "
<< standard_dev(vals) << '\n';
return 0;
}
// prompt user to get data
void get_data(std::vector<double>& vals) {
for (unsigned int i = 0; i < vals.size(); i++) {
std::cout << "Enter a value: ";
std::cin >> vals[i];
}
}
// //bubble sort values
// void Sort(double vals[], int& valCount)
// {
// for (int i=(valCount-1); i>0; i--)
// for (int j=0; j<i; j++)
// if (vals[j] > vals[j+1])
// swap (vals[j], vals[j+1]);
// }
// print sorted values
void print(const std::vector<double>& vals) {
for (auto i : vals) {
std::cout << i << ' ';
}
std::cout << '\n';
}
// compute variance
double variance(const std::vector<double>& vals) {
// was int, but your now vector is of type double
double sum = std::accumulate(vals.begin(), vals.end(), 0);
double mean = sum / static_cast<double>(vals.size());
// variance
double squaredDifference = 0;
for (unsigned int i = 0; i < vals.size(); i++)
squaredDifference += std::pow(vals[i] - mean, 2);
// Might be possible to get this with std::accumulate, but my first go didn't
// work.
return squaredDifference / static_cast<double>(vals.size());
}
// compute standard deviation
double standard_dev(const std::vector<double>& vals) {
return std::sqrt(variance(vals));
}
// //compute square root
// double SqRoot(double value)
// {
// double n = 0.00001;
// double s = value;
// while ((s - value / s) > n)
// {
// s = (s + value / s) / 2;
// }
// return s;
// }
EDIT: I did figure out the variance with an accumulator. It does require knowledge of lambdas (anonymous functions, functors). I compiled to the C++14 standard, which has been the default of major compilers for a while now.
double variance(const std::vector<double>& vals) {
auto meanOp = [valSize = vals.size()](double accumulator, double val) {
return accumulator += (val / static_cast<double>(valSize));
};
double mean = std::accumulate(vals.begin(), vals.end(), 0.0, meanOp);
auto varianceOp = [mean, valSize = vals.size()](double accumulator,
double val) {
return accumulator +=
(std::pow(val - mean, 2) / static_cast<double>(valSize));
};
return std::accumulate(vals.begin(), vals.end(), 0.0, varianceOp);
}
mean = sum / valCount; in Variance will be computed using integer math, then converted to a double. You need to convert to double first:
mean = double(sum) / valCount;
Your SqRoot function calculates an approximate value. You should use std::sqrt instead which will be faster and more accurate.
The question is
Design the grade processing program to use functions and an array. Let user enter number of grades (set the maximum to 50). Store grades in an array. Create a separate function for each calculation (total of 3 functions): 1) average grade, 2) maximum grade, 3) number of grades above the average. Display all results.
I think I got the main part, but I'm having trouble with how to write the functions, the functions are outputting one for some reason, and I'm having trouble writing the max function or how to start it.
#include <iostream>
using namespace std;
double average(double x[], int n);
double maximum(double x[], int n);
int nAboveAvg(double x[], int n);
int main()
{
double grades[50];
int ngrades;
cout<<"How many grades? (max = 50)";
cin>>ngrades;
//create for loop to get grades from user
for(int i = 0; i<ngrades; i++)
{
cout<<"Enter grade ";
cin>> grades[i];
}
//call the functions
double avg = average(grades, ngrades);
double max = maximum(grades, ngrades);
int nAbove = nAboveAvg(grades, ngrades);
//display results
cout<<"Average = "<<avg<<endl;
cout<<"# above average = "<<nAbove<<endl;
}
double average(double x[], int npts) //define the functon to recieve the array
{
double sum = 0;
for(int k = 0; k<npts; k++)
{
sum = sum +x[k];
}
return sum / npts;
}
double maximum(double x[], int npts)
{
double max = 0;
for(int i = 0; i<npts; i++)
{
if(max == npts)
{
return max;
}
if(max < npts)
{
return npts;
}
}
}
int nAboveAvg(double x[], int npts)
{
int nAboveAvg = 0;
for(int i = 0; i<npts;i++)
{
if(x[i] > npts)
{
nAboveAvg++;
}
}
return nAboveAvg;
}
Incorrect Printing
//call the functions
double avg = average(grades, ngrades);
double max = maximum(grades, ngrades);
int nAbove = nAboveAvg(grades, ngrades);
Notice that you define variables named avg and nAbove.
//display results
cout<<"Average = "<<average<<endl;
cout<<"# above average = "<<nAboveAvg<<endl;
But then you use average and nAboveAvg (the functions) when you attempt to print the results.
The correct version here would be:
cout << "Average = " << avg << endl;
cout << "# above average = " << nAbove << endl;
Compiler Warnings
When I try to compile this, the compiler emits a number of warnings. e.g.
main.cpp: In function 'int main()':
main.cpp:29:24: warning: the address of 'double average(double*, int)' will always evaluate as 'true' [-Waddress]
cout<<"Average = "<<average<<endl;
or
main.cpp:24:11: warning: unused variable 'avg' [-Wunused-variable]
double avg = average(grades, ngrades);
It is a good idea not to ignore those warnings.
Count Above Average
if(x[i] > npts)
{
nAboveAvg++;
}
You compare the value at position i with number of input values.
However, you should be comparing value at position i with the average of all the values. Hence
int nAboveAvg(double x[], int npts)
{
int count = 0;
double avg = average(x, npts);
for (int i(0); i < npts; ++i) {
if (x[i] > avg) {
++count;
}
}
return count;
}
Refactoring
You may now notice that in our program we end up calculating the average value twice. We can fix this by making our function more general -- instead of counting number of values above average, let's count the number of values above arbitrary target passed as a parameter.
int count_above(double x[], int npts, double target)
{
int count = 0;
for (int i(0); i < npts; ++i) {
if (x[i] > target) {
++count;
}
}
return count;
}
Now we can write
//call the functions
double avg = average(grades, ngrades);
double max = maximum(grades, ngrades);
int nAbove = count_above(grades, ngrades, avg);
Maximum Value
Let's think about the algorithm, and start from simplest case -- only one value in the array. In this scenario the first value is also the maximum.
double max = x[0];
Knowing that, let's consider how to find the maximum when there are 2 values in the input array. We already know the maximum of all the values before the second value. Therefore
if (x[1] > max) {
max = x[1];
}
Next step, input array with 3 values. Again, we already know the maximum of all the values before the third value. Therefore
if (x[2] > max) {
max = x[2];
}
We can see a pattern repeating here, which we can wrap in a loop.
double maximum(double x[], int npts)
{
if (npts <= 0) {
exit(-1); // Error...
}
double max = x[0];
for (int i(1); i < npts; ++i) {
if (x[i] > max) {
max = x[i];
}
}
return max;
}
Validating Input
You don't have any validation of the input passed to your functions, yet there are some obvious cases that need to be accounted for.
In all of your functions, what should happen when the npts is negative?
What's the average value of a 0 elements?
What's the maximum value of 0 elements?
A very simple way to handle those cases would be to return some special value as a result. You then have to check the results for this value every time you call the function. In many cases it may be hard to select an appropriate value for this.
Another possibility that would be accepted at a beginner level, would be simply printing some error message to console, and exiting the program. For example
if (npts <= 0) {
cerr << "Too few values in input array." << endl;
exit(-1); // Error...
}
The proper C++ approach would be to throw an exception, for example std::invalid_argument. For example
#include <stdexcept>
// ....
if (npts <= 0) {
throw std::invalid_argument("Too few values in input array.);
}
The "average" function looks good. In the last 2 lines in main, I think you want to output avg instead of average (because average is the name of the function, not the name of the variable that holds the computed value). Similarly, output nAbove instead of nAboveAvg.
The maximum function looks like an empty implementation. I don't think that will compile because it needs to (at least) return a double value.
In the nAboveAvg function, "x[i] > npts" seems like the wrong test. I think you want to compare x[i] to avg (you will want to pass avg into this function as an argument.
the purpose of this task is to find the average of an array but not within the main, I have to call a function to do the sum and show the average.
I though my code was sound but it just returns " the average is 011014F1"
I have tried a few different ways of doing the function but I've gone wrong somewhere, maybe everywhere!
Just a heads up, im just starting out with programing.
Heres my code:
#include <iostream>
#include <vector>
using namespace std;
void printArray(int theArray[], int sizeOfarray);
float average(float numbers[], float size, float arrayAverage);
int main()
{
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
printArray(array, 10);
cout << "The average is: " << average << endl;
return 0;
}
void printArray(int theArray[], int sizeOfarray)
{
for (int x = 0; x < sizeOfarray; x++)
{
cout << theArray[x] << endl;
}
}
float average(float numbers[], float size, float arrayAverage)
{
double sum = 0.0;
for (int x = 0; x < size; x++)
{
sum += numbers[x];
arrayAverage = sum / size;
}
return (arrayAverage);
}
I had the float average function initially set as a float with int for 'numbers', 'size' and 'arrayAverage' but thought i would change them all to float so they dont clash. like converting an int to a float etc..
As i said im new to this so my logic is not really there but i think im n the right tracks.
Any idea why its returning 011014F1 and numbers like that instead of just the average of 1-10?
Any tips much appreciated!
average is a function, which you need to call, and print what it returns. What you are printing now is the address of that function.
There are a number of problems here. First:
cout << "The average is: " << average << endl;
This is simply printing out the address of the average function, not calling it. What you wanted to do was:
cout << "The average is: " << average(array, 10, 0) << endl;
Second, your method signature has all kinds of type missmatches. The expected array value type is float, yet you're passing it an array of int. This won't work, as the compiler will not allow the implicit conversion from int[] to float[]. Your size argument should be an int in the method signature as well, not float, since array sizes are always integers.
Third, the arrayAverage parameter seems to have no purpose except to possibly throw off your math. You use it as a running accumulator, which is fine, but there's no reason to pass it to the function, it could just be a local value. So, your method signature should look like this:
float average(float numbers[], int size);
Finally, your math for calulating the average of an array is wrong. You do:
for (int x = 0; x < size; x++)
{
sum += numbers[x];
arrayAverage = sum / size;
}
Particularly, the arrayAverage = sum / size is wrong. Or rather, is only right during the final loop iteration. Meaning this is just wasted math. It should be:
float average(float numbers[], int size) {
double sum = 0;
for (int x = 0; x < size; x++)
{
sum += numbers[x];
}
return sum /(double)size;
}
You are not passing any thing to your function average, float average(float numbers[], float size, float arrayAverage)You should pass your array as first parameter and the size of the array in the second, the third one you dont need it , I recommand you to delete itYour function will be :
float average(float numbers[], float size)
{
float average;
double sum = 0.0;
for (int x = 0; x < size; x++)
{
sum += numbers[x];
arrayAverage = sum / size;
}
return (average);
}
and in your main you do a float averageResult = average(array, size);
qDebug()《 averageResult;
#include <iostream>
#include <vector>
using namespace std;
void printArray(int theArray[], int sizeOfarray);
int main()
{
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
printArray(array, 10);
return 0;
}
void printArray(int theArray[], int sizeOfarray)
{
for (int x = 0; x < len(theArray); x++)
{
average = average + theArray[x]
}
average = average/(len(theArray));
cout << average;
}
I am considering a society where there are an arbitrary number of people. Each person has just two choices. Either he or she stays with her current choice or she switches. In the code that I want to write, the probability that the person switches is inputted by the user.
To make clear what I am trying to do, suppose that the user tells the computer that there are 3 people in the society where the probabilities that each person chooses to switch is given by (p1,p2,p3). Consider person 1. He has probability of p1 of switching. Using him as a base for our calculation, the probability given person 1 as a base, that exactly no one in the society chooses to switch is given by
P_{1}(0)=(1-p2)*(1-p3)
and the probability using person 1 as a base, that exactly one person in the society chooses to switch is given by
P_{1}(1)=p2*(1-p3)+(1-p2)*p3.
I can't figure out how to write this probability function in C++ without writing out every term in the sum. I considered using the binomial coefficient but I can't figure out a closed form expression for the sum since depending on user input, there are arbitrarily many probabilities that need to be considered.
I have attached what I have. The probability function is only a part of what I am trying to do but it is also the hardest part. I named the probability function probab and what I have in the for loop within the function is obviously wrong.
EDIT: Basically I want to calculate the probability of choosing a subset where each element in that subset has a different probability of being chosen.
I would appreciate any tips on how to go about this. Note that I am a beginner at C++ so any tips on improving my programming skills is also appreciated.
#include <iostream>
#include <vector>
using namespace std;
unsigned int factorial(unsigned int n);
unsigned int binomial(unsigned int bin, unsigned int cho);
double probab(int numOfPeople, vector<double> probs, int p, int num);
int main() {
char correctness;
int numOfPeople = 0;
cout << "Enter the # of people: ";
cin >> numOfPeople;
vector<double> probs(numOfPeople); // Create a vector of size numOfPeople;
for (int i = 1; i < numOfPeople+1; i++) {
cout << "Enter the probability of person "<< i << " will accept change: ";
cin >> probs[i-1];
}
cout << "You have entered the following probabilities of accepting change: (";
for (int i = 1; i < numOfPeople+1; i++) {
cout << probs[i-1];
if (i == numOfPeople) {
cout << ")";
}
else {
cout << ",";
}
}
cout << endl;
cout << "Is this correct? (Enter y for yes, n for no): ";
cin >> correctness;
if (correctness == 'n') {
return 0;
}
return 0;
}
unsigned int factorial(unsigned int n){ // Factorial function
unsigned int ret = 1;
for(unsigned int i = 1; i <= n; ++i) {
ret *= i;
}
return ret;
}
unsigned int binomial(unsigned int totl, unsigned int choose) { // Binomial function
unsigned int bin = 0;
bin = factorial(totl)/(factorial(choose)*factorial(totl-choose));
return bin;
}
double probab(int numOfPeople, vector<double> probs, int p, int num) { // Probability function
double prob = 0;
for (int i = 1; i < numOfPeople; i++) {
prob += binomial(numOfPeople, i-1)/probs[p]*probs[i-1];
}
return prob;
}
For future reference, for anybody attempting to do this, the probability function will look something like:
double probability (vector<double> &yesprobabilities, unsigned int numOfPeople, unsigned int yesNumber, unsigned int startIndex) {
double kprobability = 0;
// Not enough people!
if (numOfPeople-1 < yesNumber) {
kprobability = 0;
}
// n == k, the only way k people will say yes is if all the remaining people say yes.
else if (numOfPeople-1 == yesNumber) {
kprobability = 1;
for (int i = startIndex; i < numOfPeople-1; ++i) {
kprobability = kprobability * yesprobabilities[i];
}
}
else if (yesprobabilities[startIndex] == 1) {
kprobability += probability(yesprobabilities,numOfPeople-1,yesNumber-1,startIndex+1);
}
else {
// The first person says yes, k - 1 of the other persons have to say yes.
kprobability += yesprobabilities[startIndex] * probability(yesprobabilities,numOfPeople-1,yesNumber-1,startIndex+1);
// The first person says no, k of the other persons have to say yes.
kprobability += (1 - yesprobabilities[startIndex]) * probability(yesprobabilities,numOfPeople-1,yesNumber,startIndex+1);
}
return probability;
}
Something called a recursive function is used here. This is completely new to me and very illuminating. I credit this to Calle from Math stack exchange. I modified his version slightly to take vectors instead of arrays with some help.
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
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.
Okay, this is not the answer to your problem, since you already got couple of them
How about trying something new ?
Use std::accumulate, std::sort and std::partition to achieve same goal.
#include<algorithm>
//...
struct comp
{
double avg;
comp(double x):avg(x){}
bool operator()(const double &x) const
{
return x < avg;
}
};
std::sort(arr,arr+size);
average =std::accumulate(arr, arr+size, 0.0) / size;
double *p= std::partition(arr, arr+size, comp(average));
std::cout<<"Average :"<<average <<" Closest : "<<*p<<std::endl;
This algorithm is based on the fact that std::map keeps its elements sorted (using operator<):
#include <map>
#include <iostream>
#include <math.h>
using namespace std;
double closest_to_avg(double* arr, size_t size, double avg) {
std::map<double,double> disturbances;
for(int p = 0; p < size; p++) {
disturbances[fabs(avg-arr[p])]=arr[p]; //if two elements are equally
} //distant from avg we take
return disturbances.begin()->second; //a new one
}
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
}
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.