C++ 在程序中使用布尔函数时出现问题

C++ 在程序中使用布尔函数时出现问题,c++,function,boolean,C++,Function,Boolean,我在使用布尔循环时遇到问题。我知道它们是真/假函数,但是当我运行程序时,它似乎总是返回“真”值。main是设置pass=true的那一个,还是targetHR将该值设置为true?我被难住了 #include <iostream> using namespace std; bool targetHR(int, int); int main() { int age = NULL, heartbeat; while (age >= 0) {

我在使用布尔循环时遇到问题。我知道它们是真/假函数,但是当我运行程序时,它似乎总是返回“真”值。main是设置pass=true的那一个,还是targetHR将该值设置为true?我被难住了

#include <iostream>
using namespace std;
bool targetHR(int, int);

int main()
{
    int age = NULL, heartbeat;
    while (age >= 0)
    {
        cout << "Enter your age: ";                    // Receives age from the user.
        cin >> age;
        if (age < 0)
        {
            break;
        }
        cout << "enter your heart beats per minute: "; // Receives heartbeat from user.
        cin >> heartbeat;
        bool pass = targetHR(age, heartbeat);
        if (pass = true)
        {
            cout << "You are in your target heart rate." << endl;
        }
        if (pass = false)
        {
            cout << "You are not in your target heart rate." << endl;
        }
        cout << endl;
    }

    return 0;
}
#包括
使用名称空间std;
布尔目标(int,int);
int main()
{
int age=NULL,心跳;
而(年龄>=0)
{
年龄;
如果(年龄<0)
{
打破
}
心跳;
bool pass=targetHR(年龄、心跳);
如果(通过=真)
{
库特
它似乎总是返回“真实”值

因为您没有使用,所以您正在使用,它将返回分配给检查的值,因此
pass=true
将始终是
true
,而
pass=false
将始终是
false
。您应该更改

if (pass = true)

或者只是

if (pass)
顺便说一句:有些编译器(比如)会给出警告,不要忽略它们

警告:使用赋值结果作为条件,而不使用 括号
注意:使用“==”将此赋值转换为相等比较


哇…实际上我对自己很失望…非常感谢你发现了这一点。至少我知道我走对了方向!:)@AaronTMaynard这是一个常见的错误,:)顺便说一句,一些编者会对此发出警告,不要忽视它。
if (pass == true) 
if (pass)