okay but i have to create separate functions to do a sum for the even numbers and a sum for the odd numbers. I had pretty much figured that thats how i need to do it but i cant get my function to return the right value.
okay but i have to create separate functions to do a sum for the even numbers and a sum for the odd numbers. I had pretty much figured that thats how i need to do it but i cant get my function to return the right value.
What you can do is make the even & odd variables global and create a function that takes an argument of the rolled value.
In that function, you can decide whether or not it is even, and add to the global values. After you're done rolling values, you can use another function to return the sum of even/odd, or use the global variable directly.
I'm not sure if it's very efficient to create your variables in the global scope, but you can try and see if it works out for you.
Separate functions? That seems maximum overkill for educational purposes.
Nevertheless, lets not learn global variables. They are not nice.
The static variable within a function is a neat idea, but for this task.
Reference parameters. That should be more appropriate. Parameters are passed to a function either by value (a copy), or by reference. You can pass a sum as reference and if the function modifies the parameter variable, it is actually the callers sum variable, whose value changes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
void foo( int & lhs, int rhs ) {
rhs += 3; // only local changes
lhs += rhs; // the caller's variable changes
}
int main() {
int x = 7;
int y = 42;
foo( x, y );
std::cout << "x=" << x << " y=" << y << '\n';
return 0;
}
PS. As long as you use same constant as seed, you will get the same serie of "random" numbers and thus every program run with that seed generates same output. That is why the seeding usually uses time, which could change between runs.
Thanks but i think he really wants us to use the static variable because i dont think we have learned about reference parameters. It would be really great if you could use the static variable to help
thanks
#include<iostream>
usingnamespace std;
int roll(), addOdd(int odd), 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(odd) << endl;
cout << "The sum of the even numbers is: "<< endl;
} // main
int roll()
{
return (rand() % 6)+1;
}
int addOdd(int odd)
{
staticint num1 = 0;
odd=roll();
if(odd % 2 )
num1 += odd;
return num1;
}
im getting the correct rolls but i am only receiving 0 for the sum of my odd numbers when it should be 6