using namespace std;
int roll(), rnum;
void main()
{
int i;
for (i = 1; i <=5; i++)
cout << "Your roll is : " << roll() << endl;
srand(1811);
} // main
int roll()
{
static int roll = 0;
int rnum;
rnum = rand();
roll = rnum % 6+1;
return roll;
}
Right now im tryign to create the roll of a die and then take the sum of the odd and the sum of the even rolls and display them. All i have at the moment is the roll of the die and im only geting values of 5 or 6 back.
any reason why this isnt working properly?
just the out put isnt coming out i wanted it to it was only returning 5 or 6 but that was with any random number seed. and why isnt it good practice to use namespaces?
would an if else statement work well for taking the sum of the even/odd rolls? i have to create a function to do both and i am curious if that would be the best/easiest path
You can still use it for small applications like you're doing here, but you should get used to it. Answer why is here... http://stackoverflow.com/a/1452738
So be more specific, what is it exactly you're trying to accomplish?
ok thanks. and i am trying to simulate the roll of a die using a function roll(). Then using two other functions i need to take the even numbers sum them up and display them in the main and take the sum of the odd rolls and display them in the main also.
A static variable retains it's value from function call to function call.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// http://ideone.com/cLC4Os
#include <iostream>
int f()
{
staticint n = 0; // initialization is done only the first time the function is called
return n++;
}
int main()
{
for (unsigned i = 0; i < 20; ++i)
std::cout << f() << '\n';
}
Thanks a lot. Now im trying to take the sum of the odd numbers of the rolls and return them to the main function, But all im getting is 0 when i try and display it
#include<iostream>
usingnamespace std;
int roll(), addOdd(int odd);
void main()
{
int i;
srand(1181);
for (i = 1; i <=5; i++)
{
cout << "Your roll is : " << roll() << endl;
}
cout << "The sum of the odd numbers is: " << addOdd(roll()) << endl;
cout << "The sum of the even numbers is: "<< endl;
} // main
int roll()
{
return (rand() % 6)+1;
}
int addOdd(int odd)
{
staticint num1 = 0;
if(roll()%2 )
num1 += roll();
return num1;
}
#include<iostream>
usingnamespace std;
int roll();
void main() {
int i;
int odd=0, even=0;
srand(1181);
for(i = 1; i <=5; i++) {
int r = roll();
cout << "Your roll is : " << r << endl;
if(r % 2)
even++;
else
odd++;
}
cout << "The sum of the odd numbers is: " << odd << endl;
cout << "The sum of the even numbers is: "<< even << endl;
}
int roll() {
return (rand() % 6)+1;
}