Skip to content

Instantly share code, notes, and snippets.

@jgreitemann
Last active April 27, 2017 13:50
Show Gist options
  • Save jgreitemann/be900ebc0e7a6471829b90918d07a59b to your computer and use it in GitHub Desktop.
Save jgreitemann/be900ebc0e7a6471829b90918d07a59b to your computer and use it in GitHub Desktop.
wrong.cpp
#include <iostream>
#include <vector>
double average(const std::vector<int>& v) {
double a;
size_t N = v.size();
for (size_t i = 0; i <= N; i++) {
int b = v[i];
a += b / N;
}
return a;
}
int main() {
// print multiples of 1/3 and their squares
double x = 0.0;
while (x != 6.0) {
std::cout << x << "\t" << x*x << std::endl;
x += 1./3;
}
// calculate the average over a bunch of numbers
std::vector<int> numbers = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3}; // needs C++11!
double avg = average(numbers);
std::cout << avg << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment