我试图创建一个数组,使用某个随机种子(我已经)从0-9生成20个随机数,然后计算生成的随机数的平均值。我已经得到它来执行数组罚款,但是当我去计算随机数的总和时,它会让我回到-16。我已经看了几个不同的其他事情试图帮助他们都有同样的事情我有
for (i = 0; i < SIZE; i++) {
sum += num[SIZE];}
有人可以指出我在这里做错了什么,或者在程序中的哪个位置?
#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;
}
答案 0 :(得分:2)
你在这里失踪 -
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;
}
答案 1 :(得分:0)
仅仅是为了阐述,这里是使用c ++ 14和习惯使用标准库的相同程序。
#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;
}
结果:
1 : 9 : 6 : 6 : 3 : 0 : 3 : 6 : 7 : 1 : 7 : 2 : 1 : 8 : 0 : 0 : 2 : 6 : 1 : 9
78
3.9