so i have this bit of code.. it spews segmentation faults seemingly without rhyme or reason. im doing it for HackerRank practice problems, and when i leave all the couts, it works fine, but i fail because all the extra output.
when i comment out/outright delete the cout lines, i get segmentation faults.
ive written the code in a script form, and a main fxn calling a seperate fxn to output the correct number, and still the same deal. but i know the logic is sound, because it outputs the correct answer at the bottom.
the test is that its inputting 3 lines: 5 on the first, 10 40 30 50 20 on the second, and 1 2 3 4 5 on the third. first line specifies the length of the next 2 arrays, which get filled with the values from the second and third lines. the output is supposed to be only 1 line containing the value 32.0 but i seem to only be able to get it to work with comments that change the output to at least 21 lines
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int n;
double wm=0;
vector<double>a1(n);
vector<double>a2(n);
double result(vector<double> arr1, vector<double> arr2){
double wv=0.0;
double wv2=0.0;
for(int i=0; i<n; i++){
wv+=(arr1[i] * arr2[i]);
cout<<wv<<"\n";
}
for(int i=0; i<n; i++){
wv2+=arr2[i];
cout<<wv2<<"\n";
}
return wv/wv2;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
cin>>n;
for(int i=0; i<n; i++){
cin>>a1[i];
cout<<a1[i]<<"\n";
}
for(int ii=0; ii<n; ii++){
cin>>a2[ii];
cout<<a1[i]<<"\n";
}
wm=result(a1,a2);
cout.precision(1);
cout<<fixed<<wm;
return 0;
}
*******************THAT IS Main() CALLING Result(), THIS IS THE SCRIPT FORMAT**********
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
vector<double>a1(n);
vector<double>a2(n);
double wv=0.0;
double wv2=0.0;
double wm=0;
cin>>n;
for(int i=0; i<n; i++){
cin>>a1[i];
cout<<a1[i]<<"\n";
}
for(int ii=0; ii<n; ii++){
cin>>a2[ii];
cout<<a2[ii]<<"\n";
}
for(int i=0; i<n; i++){
wv+=a1[i] * a2[i];
cout<<wv<<"\n";
}
for(int i=0; i<n; i++){
wv2+=a2[i];
cout<<wv2<<"\n";
}
wm=wv/wv2;
cout.precision(1);
cout<<fixed<<wm;
return 0;
}