1000 dice output 2-12 weird negative number
Apr 24, 2019 at 10:00pm UTC
I wrote a program to output 2 through 12 of 1000 dice rolls and it does everything it needs to do but it is putting out a large negative number after outputting 2-12 for some reason.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
// Two Dice.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
#include <array>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int roll{ 0 };
int arolls{ 0 };
int croll[11];
srand(static_cast <unsigned int >(time(0)));
std::cout << "Prepare for 1000 dice rolls!\n" ;
for (int i{ 0 }; i < 1000; i++)
{
roll = 1 + rand() % (6);
arolls += roll;
if (i > 1 && i < 13)
{
croll[i - 2] = roll;
}
}
cout << "\nThe following are rolls 2-12.\n\n" ;
for (int i{ 0 }; i < 12; i++)
{
cout << " " << croll[i];
}
arolls = arolls / 1000;
cout << "\n The average of 1,000 rolls is " << arolls << " .\n\n" ;
}
Apr 24, 2019 at 10:12pm UTC
You only filled array elements croll[0] to croll[10].
Then you tried to print out croll[0] to croll[11].
Apr 24, 2019 at 10:12pm UTC
32:25 warning: iteration 11u invokes undefined behavior [-Waggressive-loop-optimizations]
On last iteration the i==11 on line 32.
The croll has only 11 elements.
There is no element
croll[11]
.
You print content of memory that is
after the array croll as if it were an int.
We have no idea what that memory has.
Apr 24, 2019 at 10:17pm UTC
Thank you for the help that was the problem!
Topic archived. No new replies allowed.