I'm trying to create an array that generates 20 random numbers from 0-9 using a certain random seed(which i have already), then calculates the average of the random numbers generated. I've gotten it to execute the array fine, but when i go to calculates the sum of the random numbers, it gives me back -16. I've looked at several different other things to try to help and they all have the same thing that i've got
for (i = 0; i < SIZE; i++) {
sum += num[SIZE];}
Can someone point out what im doing wrong here or else where in the program?
#include <iostream>
#include <cstdlib>
using namespace std;
int main() // Creates the array
{
srand(2622); // random seed
const int SIZE = 20;
int num[SIZE], i, sum = 0;
for (i = 0; i < 20; i++) {
cout << rand() % 10 << " : "; // generates random numbers 0-10
}
cout << endl;
for (i = 0; i < SIZE; i++) {
sum += num[SIZE];
}
cout << sum << endl;
return 0;
}
You are missing at here --
sum += num[SIZE]; should be sum += num[i];
#include <iostream>
#include <cstdlib>
using namespace std;
int main() // Creates the array
{
srand(2622); // random seed
const int SIZE = 20;
int num[SIZE], i, sum = 0;
for (i = 0; i < 20; i++) {
num[i] = rand() % 10 ;
cout << num[i] << " : "; // generates random numbers 0-10
}
cout << endl;
for (i = 0; i < SIZE ; i++ ) {
sum += num[i];
}
cout << sum << endl;
return 0;
}
Just for exposition, here's the same program using c++14 and idiomatic use of the standard library.
#include <iostream>
#include <numeric>
#include <random>
#include <functional>
using namespace std;
template<class Iter>
std::ostream& emit_range(std::ostream& os, Iter first, Iter last,
const char* inter_sep = " : ",
const char* terminator = "\n")
{
auto sep = "";
while (first != last) {
os << sep << *first;
++first;
sep = inter_sep;
}
return os << terminator;
}
int main() // Creates the array
{
// function object to create a pre-seeded pseudo-random sequence
auto next_number = [eng = std::default_random_engine(2622),
dist = std::uniform_int_distribution<int>(0, 9)]() mutable
{
return dist(eng);
};
constexpr int SIZE = 20;
int num[SIZE];
// generate the random numbers
std::generate(std::begin(num), std::end(num), next_number);
// compute the sum
auto sum = std::accumulate(std::begin(num), std::end(num), 0,
std::plus<>());
// compute the average
auto average = double(sum) / SIZE;
// print results
emit_range(cout, std::begin(num), std::end(num));
cout << sum << endl;
cout << average << endl;
return 0;
}
results:
1 : 9 : 6 : 6 : 3 : 0 : 3 : 6 : 7 : 1 : 7 : 2 : 1 : 8 : 0 : 0 : 2 : 6 : 1 : 9
78
3.9
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.