我刚刚学习了C++函数; 我可以在函数返回值上使用if语句吗?

Sag*_*tic 7 c++ function

我感到困惑的是关于isNumPalindrome()函数.它返回一个布尔值true或false.我怎么想使用它,所以我可以显示它是否是回文.对于前者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;
}
Run Code Online (Sandbox Code Playgroud)

mik*_*ked 12

函数的返回值可以像相同类型的变量一样使用.

你的主程序应该是这样的:

int main()
{
  int num=askNumber();
  bool isPal=isNumPalindrome(num);
  if (isPal)
  {
    //do something
  }
  else
  {
    //do something else
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

或者你可以更简洁:

int main()
{
  if (isNumPalindrome(askNumber()))
  {
    //do something
  }
  else
  {
    //do something else
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

您不想做的是使用您定义的那些全局变量.在更复杂的程序中,这将成为一场灾难.

编辑:您需要确保编辑isNumPalindrome函数以接受它正在使用的数字:

bool isNumPalindrom(int num)
{
   ...
}
Run Code Online (Sandbox Code Playgroud)


Pau*_*tos 8

是的,你可以做这样的事情.

其实你可以做到......

if (isNumPalindrome()) { ... }
Run Code Online (Sandbox Code Playgroud)