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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2472868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:34:26  来源:igfitidea点击:

I just learned about C++ functions; can I use if statements on function return values?

c++function

提问by Sagistic

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.";

我对 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;
}

回答by miked

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:

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

bool isNumPalindrom(int num)
{
   ...
}

回答by Paulo Santos

Yes, you can do such thing.

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

Actually you could do just...

其实你可以只...

if (isNumPalindrome()) { ... }

回答by Rachel

if(isNumPalindrome())
{
    cout << "Your number is a palindrome";
}
else
{
    cout << "Your number is not a palindrome";
}

回答by Chris H

when a function returns a type you can think of that function as being replaced by the return value and type. so for you:

当函数返回一个类型时,您可以认为该函数被返回值和类型替换。所以对你来说:

isNumPalindrome() -> {true/false}

isNumPalindrome() -> {true/false}

so you can write for example:

所以你可以写例如:

if(isPalindrome())
  cout<<"it is!"<<endl;
else
  cout<<"it is not :("<<endl;

回答by outis

First, you shouldn't use globalsfor numand pwr; you should pass them as arguments to functions:

首先,你不应该numand使用全局变量pwr;您应该将它们作为参数传递给函数:

bool isNumPalindrome(int num);
...
num = askNumber();
isNumPalindrome(num);

Second, there's no need to compare a boolean value with true(or false); simply use the boolean value.

其次,不需要将布尔值与true(或false)进行比较;只需使用布尔值。

It's hard to tell what exact syntax you're trying to use in your example "if" statement, but one thing you can't do is have an "if" statement in an expression. In C++, there are expressions and statements. Expressions have values; statements don't.

很难说出您在示例“if”语句中尝试使用的确切语法,但您不能做的一件事是在表达式中包含“if”语句。在 C++ 中,有表达式和语句。表达式有值;陈述没有。

// valid
if (isNumPalindrome(num)) {
    std::cout << '"' << num << "\" is a palindrome." << std::endl;
} else {
    std::cout  << '"' << num << "\" is not a palindrome." << std::endl;
}

// invalid
std::cout << '"' << num << (if (isNumPalindrome(num)) {
    "\" is a palindrome.";
} else {
    "\" is not a palindrome.";
}) << std::endl;

// valid, but not recommended
std::cout << '"' << num << "\" is " << (isNumPalindrome(num) ? "" : "not ") << "a palindrome." << std::endl;

For the ternary operator (?:), read "To ternary or not to ternary?"

对于三元运算符 (?:),请阅读“要三元还是不要三元?

回答by Corwin

As many people have stated, the return value of a function essentially becomes the function's value.

正如很多人所说,函数的返回值本质上就是函数的值。

Here's an example of a ternary operation for printing the result.

这是用于打印结果的三元运算的示例。

cout << "The number " << (isNumPalindrome()) ? "is a palindrome" : "is NOT a palindrome";

This is a bit weird looking for a lot of beginners, but it shows how ternary operators can be used to print conditional responses.

对于很多初学者来说,这有点奇怪,但它展示了如何使用三元运算符来打印条件响应。

回答by Dominic.wig

yet another solution ;-)

另一个解决方案;-)

#include <iostream>
#include <sstream>
#include <algorithm>

bool is_palindrome( const int num )
{
    std::ostringstream os;
    os << num;
    const std::string& numStr = os.str();
    std::string reverseNumStr = numStr;
    std::reverse( reverseNumStr.begin(), reverseNumStr.end() );
    const bool result = ( numStr == reverseNumStr );
    return result;
}

int main()
{
    int num = 0;
    std::cout << "Enter an integer in order to determine if it is a palindrome: ";  
    std::cin >> num; 

    std::string inset;
    if( !is_palindrome( num ) )
    { 
        inset = "not ";
    } 
    std::cout << "It is " << inset << "a palindrome." << std::endl; 
}

回答by sinek

In a single sentence:

一句话概括:

"As the condition of the ifstatement you can use any expressionwhose result, once when expression is evaluated, can be implicitlyconverted to 'bool'."

“作为if语句的条件,您可以使用其结果的任何表达式,一旦表达式被评估,就可以隐式转换为 ' bool'。”

回答by liewl

You could call isNumPalindrome() inside askNumber(), and have the returned value from isNumPalindrome() be used in a conditional test. It's better to pass num as an argument to isNumPalindrome though: isNumPalindrome(int num)

您可以在 askNumber() 中调用 isNumPalindrome(),并将 isNumPalindrome() 的返回值用于条件测试。最好将 num 作为参数传递给 isNumPalindrome: isNumPalindrome(int num)

int askNumber()
{
 cout << "Enter an integer in order to determine if it is a palindrome: " ; 
 cin >> num;
 if(isNumPalindrome(num)){
   cout << "it is a palindrome";
 }
 cout << endl;

 return num;
}

then main can call only askNumber()

那么 main 只能调用 askNumber()