Originally Posted by
Salem
> -Write a function called IsEven() that returns true if an integer passed to it is even
You're missing the "is passed" part.
What you have at the moment is a global variable called nValue.
What is even more confusing (for you) is that you also have a local variable called nValue as well.
main uses the local variable, and isEven uses the global variable.
Oh, and put
using namespace std;
just once, after all the include's.
Edit
+1 for using code tags right first time.
Thanks for the explanation. This makes thing a lot clearer now!
Oh, and it's not hard to get the tags right, especially if you take a moment to preview prior to posting.
Originally Posted by
Elysia
...Btw, this code
if (nValue %2 ==0)
return true;
else
return false;
can be reduced to simply
return (nValue %2 == 0);
because it's a boolean expression. That is, nValue %2 == 0 returns true or false, which you check with your if statement. But since it already returns true or false (what you want), why not directly return it?
Thanks for the tip Elysia, it makes perfect sense.
So this is the revised code, and it works fine. Any more tips and suggestions are most welcome. I am pleasantly surprised as to how helpful these forums have been.
Code:
#include "stdafx.h"
#include <iostream>
using namespace std;
bool IsEven (int nValue)
{
return (nValue %2 == 0);
}
void PrintResult (int nResult)
{
cout<< "Your result is:" << nResult << endl;
}
int GetUserInput ()
{
cout << "Enter an integer" << endl;
int nValue1;
cin >> nValue1;
return nValue1;
}
int main ()
{
int nInput= GetUserInput ();
int nResult= IsEven (nInput);
PrintResult (nResult);
}