I just learned about C++ functions; can I use if statements on function return values?
c++, function
Solution
The return value for a function can be used just like a variable of the same type.
Your main program should look something like this:
int main()
{
int num=askNumber();
bool isPal=isNumPalindrome(num);
if (isPal)
{
//do something
}
else
{
//do something else
}
return 0;
}
or you could be even more succinct:
int main()
{
if (isNumPalindrome(askNumber()))
{
//do something
}
else
{
//do something else
}
return 0;
}
What you don't want to do is use those global variables you defined. In more complicated programs that will be a recipe for disaster.
Edit: you'll want to make sure you edit your isNumPalindrome function to accept the number it's working with:
bool isNumPalindrom(int num)
{
...
}
Problem
What I am confused on is about the isNumPalindrome() function. It returns a boolean value of either true or false. How am I suppose to use that so I can display if it's a palindrome or not. For ex. `if (isNumPalindrome == true) cout << "Your number is a palindrome"; else cout << "your number is not a palindrome.";` ``` #include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { return 0; } #include <iostream> #include <cmath> using namespace std; int askNumber(); bool isNumPalindrome(); int num, pwr; int main() { askNumber(); return 0; } bool isNumPalindrome() { int pwr = 0; if (num < 10) return true; else { while (num / static_cast<int>(pow(10.0, pwr)) >=10) pwr++; while (num >=10) { int tenTopwr = static_cast<int>(pow(10.0, pwr)); if ((num / tenTopwr) != (num% 10)) return false; else { num = num % tenTopwr; num = num / 10; pwr = pwr-2; } } return true; } } int askNumber() { cout << "Enter an integer in order to determine if it is a palindrome: " ; cin >> num; cout << endl; if(isNumPalindrome(num)) { cout << "It is a palindrome." ; cout << endl; } else { cout << "It is not a palindrome." ; cout << endl; } return num; } ```