C++ 如何正确使用布尔函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21608051/
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:43:44  来源:igfitidea点击:

How to correctly use Boolean functions?

c++

提问by Fredrik E

I'm having trouble with the following assignment, mostly because I don't understand how a Boolean function works. "Write a function called Divisible that takes in two numbers as parameters. Return True if the first number is evenly divisible (no remainder) by the second number. Otherwise return False. Hint: Use %"

我在执行以下分配时遇到问题,主要是因为我不了解布尔函数的工作原理。“编写一个名为 Divisible 的函数,它接受两个数字作为参数。如果第一个数字可以被第二个数字整除(没有余数),则返回 True。否则返回 False。提示:使用 %”

Currently what I have is:

目前我所拥有的是:

int Divisible()
{
     int firstNum;
     int secondNum;
     int result;
     cout << "Please enter any integer: ";
     cin >> firstNum;
     cout << "Please enter another integer: ";
     cin >> secondNum;
     result == firstNum%secondNum;
}

I'm not sure what to do beyond that. I thought I could assign bool = 0 as true but that doesn't appear to be the case. I'm still very new to C++ so any help would be appreciated.

我不知道除此之外还能做什么。我以为我可以将 bool = 0 指定为 true,但情况似乎并非如此。我对 C++ 还是很陌生,所以任何帮助将不胜感激。

回答by Fredrik E

The question asks you to write a method that takes the numbers as parameters, not let's you input them from standard input.

这个问题要求你编写一个以数字为参数的方法,而不是让你从标准输入中输入它们。

Boolean is a type of its own in c++, so you want the method to return bool and not int. An easy to read solution:

Boolean 在 C++ 中是它自己的一种类型,因此您希望该方法返回 bool 而不是 int。一个易于阅读的解决方案:

bool Divisible(int a, int b) {
    int remainder = a % b; // Calculate the remainder of a and b.

    if(remainder == 0) {
        return true; //If the remainder is 0, the numbers are divisible.
    } else {
        return false; // Otherwise, they aren't.
    }
}

Or more concise:

或者更简洁:

bool Divisible(int a, int b) {
    return (a % b) == 0;
}

Even more concise:

更简洁:

bool Divisible(int a, int b) {
    return !(a % b);
}

回答by smac89

In methods that return boolean, you want to first determine what the value of the result will be when the method returns true, and then use the ==operator to evaluate any result you get against the acceptable result.

在返回布尔值的方法中,您首先要确定当方法返回 true 时结果的值是什么,然后使用==运算符根据可接受的结果评估您得到的任何结果。

So in your case, you are trying to determine whether to return true or false depending on if the first number is evenly divisible by the second.

因此,在您的情况下,您试图根据第一个数字是否可以被第二个数字整除来确定是返回 true 还是 false。

First thing you do is you take a case that should work, ex:

你做的第一件事是你拿一个应该有效的案例,例如:

  • 4, 2
  • 4, 2

How do you know 4is divisible by 2? Well this means that if I divide 4 by 2, then the remainder should be zero. This is what the %operator returns. If you do 4 % 2the value is zero.

你怎么知道4被 整除2?那么这意味着如果我将 4 除以 2,那么余数应该为零。这是%运算符返回的内容。如果您这样做,则4 % 2该值为零。

Ok so now you have the correct result so what you simply do now is to evaluate any result you get against the accepted result like so:

好的,现在您有了正确的结果,所以您现在要做的就是根据接受的结果评估您得到的任何结果,如下所示:

int isDivisible(int a, int b)
{
    const int acceptedAnswer = 4 % 2;
    if ( a % b == acceptedAnswer )
        return 1;
    return 0;
}

And there you have it, any value you get that does not equal your accepted answer will return 0or not equal (!=)and any other answer will return 1or equal (==)

你有它,你得到的任何不等于你接受的答案的值都将返回,0或者not equal (!=)任何其他答案将返回1equal (==)

回答by smac89

When creating functions or using them always remember to start with the signature.

创建函数或使用它们时,请始终记住从签名开始。

Think what will this function need to work with, and what will it return. You need to return if something is true or false, which are values of data type bool. Just like in a conditional such an if statement you may use Boolean operators like ==, !=and etc.

想想这个函数需要处理什么,它会返回什么。如果某些内容为真或假,您需要返回数据类型的值bool。就像在诸如 if 语句的条件中一样==,您可以使用布尔运算符,例如, !=等等。

So you need to return a bool and check if two numbers are divisible. Therefore:

所以你需要返回一个 bool 并检查两个数字是否可以整除。所以:

bool Divisible(int a, int b){

          // == boolean operator that will return true if a%b evaluates to 0
          // false if not
          return (a % b) == 0 
}

Once you start thinking of functions this way, every program becomes one great puzzle!

一旦你开始以这种方式思考函数,每个程序都会变成一个大难题!

回答by Elliott Frisch

You don't return; or assign a result...

你不回来;或分配结果...

result = firstNum%secondNum;
return (result == 0); // Assuming you want 0 as true.

In general, the value 0is false and any value that is not (!0) is true. By convention, that is 1.

通常,该值为0假,任何不为 ( !0) 的值为真。按照惯例,即1.

回答by Wajahat

what you have done is correct but in last line you are comparing an uninitialized integer with result (remainder of division).

您所做的是正确的,但在最后一行中,您将未初始化的整数与结果(除法的余数)进行比较。

set int result=0;and then do this:

设置int result=0;然后执行以下操作:

return result==firstNum%secondNum; // checks if remainder is zero (true if zero)

you could also simply do return (firstNum%secondNum)==0

你也可以简单地做 return (firstNum%secondNum)==0

Furthermore, your assignment asks for a function that takes in two numbers as parameters (input arguments). So your function prototype should be something like:

此外,您的赋值要求一个接受两个数字作为参数(输入参数)的函数。所以你的函数原型应该是这样的:

bool Divisible(int a, int b);

and you should use a and b in the function instead of taking input from stdin as you are doing right now.

并且您应该在函数中使用 a 和 b 而不是像您现在所做的那样从 stdin 获取输入。

回答by Vlad from Moscow

In the assignment there is clear written that the function must have two parameters. So the function could look the following way (C++)

在赋值中明确写到函数必须有两个参数。因此该函数可能如下所示(C++)

inline bool Divisible( int n, int m ) { return ( n % m == 0 ); }

or (C)

或 (C)

inline _Bool Divisible( int n, int m ) { return ( n % m == 0 ); }

In the last case you may substitute return type _Bool for int. In the firt case that is when C++ is used it is better to use return type bool. The request to enter two numbers shall be outside the function. The function only allows to determine whether one number is divisible by other number.

在最后一种情况下,您可以将返回类型 _Bool 替换为 int。在使用 C++ 的第一种情况下,最好使用返回类型 bool。输入两个数字的请求应在函数之外。该函数只允许判断一个数是否能被另一个数整除。

回答by Vlad from Moscow

boolis a type that can hold only two values: trueand false. You use it for expressing truth values, as whether a number divides another or not.

bool是一种只能保存两个值的类型:truefalse。您可以使用它来表达真值,例如一个数字是否可以整除另一个数字。

In your case, the function could have been implemented as follows:

在您的情况下,该功能可能已实现如下:

bool is_divisible(int a, int b)
{
    return a % b == 0;
}