0

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Wow... I am actually rather dissapointed in myself... Thank you very much for spotting this. At least I know I was on the right track! :)
@AaronTMaynard This is a common mistake, :) BTW, some compliers would give a warning for this, don't ignore it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.