简体   繁体   中英

Having trouble with a Collatz Conjecture test in C

I am trying to create a code that will take the number 2 to 100, and test each for the collatz conjecture. The goal is that for each number, if it is even, divide it by two, and if it is odd, then multiply it by 3 and add 1. It prints each step, and each number should stop testing if it reaches 1. Why doesn't it work?

#include <stdio.h>

int main()
{
    int number, position;
    position == 2;
    number == 2;
    while (position <= 100)
    {
        while (number != 1)
        {
            if (number % 2 == 0)
            {
                number = number/2;
                printf("%d\n", number);
            }
            else if (number % 2 != 0)
            {
                number = number*3;
                number = number + 1;
                printf("%d\n", number);
            }
        }
    position = position + 1;
    number = position;
    }
}

It prints recurring Os

Fix the == vs = :

position = 2;
number = 2;

Also, the else if is unnecessary. The opposite of even is odd , so a plain else will suffice:-)

You have set position and number with a double equal == (Comparision Operator) instead of using single equal = (Assignment Operator) so that the algorithm is comparing them instead of assigning a value. The assignment should look like this:

position = 2;
number = 2;

Also you can do it when you first define them:

int number=2, position=2;

Apart from that the code is correct, the only thing to highlight is that you don´t need to use else if because it can just be even or odd so a single else would be enough.

Hope I´ve helped:-)

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