C-language prime number code question

Asked 2 years ago, Updated 2 years ago, 27 views

Find a user-defined function that returns the maximum prime number less than the positive integer (X) entered...

We're trying to get the same prime number as 3, 7, etc. When you enter X, the user-defined function uses the for statement to check all numbers smaller than X for decimals. I don't know much about grammar. An error appears stating that the variable result has not been initialized. I think it's because the for statement doesn't work properly, but is there any error in the for statement in the user-defined function?

#include <stdio.h>

unsigned int prob1(unsigned int X);

int main()
{
    unsigned int X=10;
    unsigned int result;

    result = prob1(X);

    printf("%d\n", result);
}

unsigned int prob1(unsigned int X)
{
    unsigned int dump=0, result;
    unsigned int i=0, j;

    for(i=X-1;i>=3;i--)
    {
        for(j=i-1;j>=2;j--)
        {
            if((i%j)!=0)
            {
                continue;
            }
            else if((i%j)==0)
            {
                dump=i;
                break;
            }
        }

        if(dump==0)
        {
            result=i;
            break;
        }

    }


    return result;

c

2022-09-22 20:43

1 Answers

The function prob1 can return the garbage value. If prob1 does not meet the dump==0 condition, the result will be returned with the garbage value.

    unsigned int dump=0, result=0;

Please initialize the value of the result as shown in .


2022-09-22 20:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.