我的任務是鍵入並讀取()幾個雙變量並將它們存儲在向量中,然後函數compute()應該計算存儲在向量中的所有變量的總和及其平均值。我已經修復了這些功能,並且它們運行良好。問題是最終的函數print()..函數應該輸出結果 - 'sum'和'average'變量。但是我的print()代碼不能正常工作並打印出錯誤的數字。這裏是我的代碼:在C++中的函數之間傳遞變量
#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;
}
在此先感謝您的幫助,我明白我的mystake在功能之間的變量傳遞,但我花了整整一天的調試和閱讀教程沒有任何的運氣。
查找參考文獻。 –