简体   繁体   中英

Trouble using a Boolean function in a program

I am having trouble using a boolean loop. I understand that they are true/false functions, however I when I run my program, it seems to always return the "true" value. Is main the one setting pass = true, or is it targetHR that set the value to true? I am stumped.

#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;
}

My goal is to have targetHR be the one that does the calculations, as well as tell the main function if true/false. I want main to only have a response that is dependent on targetHR .

bool targetHR(int age, int heartbeat)
{
    double maxHR, minTHR, maxTHR;
    maxHR = 220 - age;
    minTHR = maxHR * 0.60;
    maxTHR = maxHR * 0.70;
    // Debugging purposes.
    // cout << "Max heartrate: " << maxHR << endl << "Min Target HR: " << minTHR << endl << "Max Target HR: " << maxTHR << endl;

    if (heartbeat < minTHR || heartbeat > maxTHR)
    {
        return false;
    }
    else
    {
        return true;
    }
}

I have tried solving the issue by changing true/false with 1/0, but that did not fix my problem, so I am assuming that is not the issue.

it seems to always return the "true" value

Because you're not using Comparison operator , you're using Assignment operator , which will return the value assigned for check, so pass = true will always be true , and pass = false will always be false . You should change

if (pass = true)

to

if (pass == true) 

or just

if (pass)

BTW: Some compilers (such as clang ) will give warnings for it, don't ignore them.

warning: using the result of an assignment as a condition without parentheses
note: use '==' to turn this assignment into an equality comparison

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM