I've just started trying to learn C++ and am using the book "C++ by dissection"
Been trying to generate a list of 100 random integers and its corresponding sum but i'm quite certain that the sum i get is wrong (only 9 digits vs the 10 digits of the random integers). Any help would be appreciated!
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int how_many = 100;
int sum;
cout << "Print " << how_many
<< " random integers." << endl;
for (int i = 0; i < how_many; ++i)
{
cout << rand() << '\t' << '\t';
cout << endl;
sum = sum + rand();
}
cout << "the sum is " << sum << endl;
}
I'm guessing that my equation "sum = sum + rand()" is wrong but i don't know why.
cout << rand() << '\t' << '\t'; // get and print a random number (why those tabs?)
cout << endl;
sum = sum + rand(); // here you will get a new random number, different from that you have previously printed on screen
I agree with jsmith.. There's nothing wrong with your equation, but sum(as an integer) can't hold the potential huge number that you get.. Instead you get a garbage value. Try declaring sum as a double. That should solve the problem
so apparently there are 2 solutions to the problem
1. i only need to define sum to hold a larger value
2. rand() in "sum = sum + rand()" gives me a new set of integers different from that of the previous rand() that was printed
anybody able to clarify?
Thanks!
And i'm completely new to this forum.. this place rocks! answers come in so quickly!
I guess one way to do it is to use a temporary variable, which will save the value that rand() returns. This way you'll be able to monitor rand()'s and get the sum you want.
#include <iostream>
#include <math.h>
usingnamespace std;
int main()
{
int how_many = 100;
longint sum = 0;
int temporary;
cout << "Print " << how_many
<< " random integers." << endl;
for (int i = 0; i < how_many; ++i)
{
temporary = rand();
cout << temporary << endl;
sum = sum + temporary;
}
cout << "the sum is " << sum << endl;
return 0;
}
It is worth noting that if X and Y are uniformly distributed (discrete or continuous) random
variables across ranges Rx and Ry, regardless of whether Rx == Ry, the sum X + Y is not
uniformly distributed.
I'm trying to learn the basics of c++ on my own, and was working through the exercises of a text. So i'm not too concerned about the applicability at the moment, but as to how the system works!
that said.. the sum of a list of random numbers is made up of the numbers on the list. So if i can list out the random numbers the sum shouldn't be random any more right?