简体   繁体   中英

New To C and trying to make a collatz conjecture program but it's not working and i don't know why

This is my attempt at a c program which solves the collatz conjecture i am really new to c and would like to know why my code is not working

#include <stdio.h>
int main()
{
    int num = 0;
    int count = 0;
    printf("Enter your number: ");
    scanf("%d", &num);
    while ("%d" != 2,num);{
        if (num %2 == 0)
        {
                num = num / 2;
                printf("%d", num);
                count = count + 1;

        }
        else
        {
                num = num * 3 + 1;
                printf("%d", num);
                count = count + 1;
        }
    }

    if (num == 1);
    {
        printf("%d", count);
    }
    return 0;
}

Your syntax is wrong.

The condition in while should be a boolean condition, and num variable should be different than 1. I edit also printfs to be more suggestive and add a new line to them. I excluded the last if condition because it was redundant. When the code finish while loop the num variable will be 1.

I think what you are trying to do is this:

#include <stdio.h>
int main()
{
    int num = 0;
    int count = 0;
    printf("Enter your number: ");
    scanf("%d", &num);
    while (num != 1)
    {
        if (num %2 == 0)
        {
                num = num / 2;
                printf("num = %d\n", num);
                count = count + 1;

        }
        else
        {
                num = num * 3 + 1;
                printf("num = %d\n", num);
                count = count + 1;
        }
    }

    printf("count = %d", count);
    return 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