简体   繁体   中英

How to count the number of odd numbers in a Hailstone Sequence using C++

I am currently enrolled in an Into to C++ class in college. One of the assignments requires students to create a C++ program that prompts the user for an integer then displays the hailstone sequence beginning from the value inputed and ending at 1. In addition, it is also required that the program outputs the following: 1. the length of the sequence 2. the largest number in the sequence 3. the number of odd integers in the sequence 4. the longest sequence from 1 to the inputted value n

I have completed the all of the requirements, except for the 3rd item. Below is a copy of the function I had created to accomplish this task.

int oddCont(int n)
{

    int count = 0; 
    while (n != 1) 
    {
        if (!isEven(n))
        {
            count++; 
        }
        n = nextVal(n);
    }

    return count; 
}

The issue that I am having is that this function returns one less than the correct number. For example, if there are four odd numbers, it prints 3. I have also discovered that the issue, specifically, is that the function does not count the last number in the sequence, 1, as an odd integer. So, if I were to get the hailstone sequence beginning with 7 and ending with one, it would count all the odd numbers, but 1 (7, 11, 17, 13, and 5). I am, however, unsure how to amend this.

I would really appreciate any advice to help resolve this issue. Also, for your convenience, I will include the definitions for the other two functions invoked within the above one.

//returns true if n is even and false otherwise
bool isEven(int n) 
{
    if (n % 2 == 0)
    {
        return true; 
    }
    else 
    {
        return false; 
    }

}

//returns hailstone sequence value that proceeds n
int nextVal(int n)
{
    if (isEven(n))
    {
        return n/2;
    }
    else 
    {
        return 3 * n + 1; 
    }
}

Since the loop stops as soon as n becomes 1, you know that there is always one more odd number. So the change is simple:

return count + 1;

Note that you can reduce your isEven() function to a single line:

return n % 2 == 0;

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