简体   繁体   中英

c++ vector not being found when passed to function?

EDIT: Apparently this code is fine, but for some reason is not working on Atom's built-in c++ compiler.

So I'm trying to create a program in C++ that takes an array and then returns the average of all the numbers in that array. I've since learned that any array passed into a function "decay" into pointers, and was pointed in the direction of vectors. However, I'm stuck on this code, which doesn't seem to print out anything. I've tried debugging by having it print during the for loop, but it still doesn't print anything. Does that mean it's not finding the vector size at all, and simply ending before it starts? It's not throwing any errors, so I'm not sure. How do I get this to output the average of this vector? Thank you in advance!

#include <iostream>
#include <vector>
using namespace std;

vector<int> arr = {1, 2, 3, 4, 5, 6};

void avg(vector<int> array){
  double total = 0;
  for (int i = 0; i < array.size(); i++){
    total += array[i];
  }
  double average = total/array.size();
  cout << average;
}

main(){
avg(arr);
}

You output stream is probably buffered. Try add a newline at the end like so:

cout << average << endl;
Below code is working for me, I guess you forgot to pause the result screen

#include <iostream>
#include <vector>
using namespace std;

vector<int> arr = {1, 2, 3, 4, 5, 6};

void avg(vector<int> array) {
  double total = 0;
  for (int i = 0; i < array.size(); i++) {
    total += array[i];
  }
  double average = total / array.size();
  cout << average;
}

int main() {
  avg(arr);
  system("pause");
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM