How to send variables from one function to another

Hello,

My task is to type and read() several double variables and store them in vector, then the function compute() should calculate the sum of all variables stored in the vector and their average. I have fixed these functions and they work well. The problem is with the final function print() .. the function should print out the result - 'sum' and 'average' variables. But my code for print() is not working properly and prints out wrong numbers. Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iomanip>
#include <cstdlib>
#include <iostream>
#include <vector> 
using namespace std;

vector<double> read(){//this function works fine
	cout << "Write some numbers with space between them?" << endl;
	double numz;
	vector<double> myvector;
	do {
    cin >> numz;
    myvector.push_back (numz);
	} while (numz);
	return myvector;
}  

void compute(double average, double sum, vector<double> &myvector){//this function works fine
//if i put cout in this function it calculates correctly
	vector<double>::iterator it;
	for ( it=myvector.begin() ; it < myvector.end()-1; it++ ){
    sum += *it;
    }
	average = sum/myvector.size();

}

void print(double average, double sum){//this is printing out wrong numbers
	cout.precision(2); 
	cout << sum << endl;
	cout << fixed  << average << endl;
}


int main (){
	vector<double> myvector = read();
	double average;
	double sum;
	compute(average, sum, myvector);
	print(average, sum);//this is printing out wrong numbers

	system("pause");
  return 0;
}


Thanks in advance for any help, i understand that my mystake is in variable passing between functions but i have spent the whole day debugging and reading tutorials without any luck.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
int i =0;

int f(int i)
{
    ++i;
    return i;
}


int main()
{
	f(i); //i is still 0
}



just an example to show you the problem.
f(i) gets a copy of i, so the ++i only works on the copy, but doesnt change the global variable i.
if you want to change i use i=f(i) or change the function to int f(int &i)
Last edited on
Use the address of operator for the average and sum variable on line 18 as you did with the vector. That should change the value of average and sum back in main.
Topic archived. No new replies allowed.