C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了我刚刚学习了C函数;我可以在函数返回值上使用if语句吗?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我感到困惑的是关于isNumpalindrome()函数.它返回一个布尔值true或false.我怎么想使用它,@R_561_9447@显示它是否是回文.对于前者if(isNumpalindrome == truE)cout<< “你的号码是回文”;别的cout<< “你的号码不是回文.”;
#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;
}

解决方法

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

你的主程序应该是这样的

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

  return 0;
}

或者你可以更简洁:

int main()
{
  if (isNumpalindrome(asknumber()))
  {
    //do something
  }
  else
  {
    //do something else
  }

  return 0;
}

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

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

bool isNumPalindrom(int num)
{
   ...
}

大佬总结

以上是大佬教程为你收集整理的我刚刚学习了C函数;我可以在函数返回值上使用if语句吗?全部内容,希望文章能够帮你解决我刚刚学习了C函数;我可以在函数返回值上使用if语句吗?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。