函数返回的值与收到的值不同。为什么?

时间:2013-09-07 17:58:25

标签: c

我从函数isprime返回值1或0(当它不是素数时为0,当它是素数时返回1)但是当我打印x的返回值(isprime的返回值)时它与我返回的值不同来自isprime。为什么呢?

#include<stdio.h>
int isprime(int b);

main()
{
    int a,rem,i;

    printf("enter the number");
    scanf("%d", &a);

    for(i = 1; i < a; i++)
    {

        rem = a % i;
        if(rem == 0)
        {
            int x = isprime(i);
            printf(" value of x returned for i = %d is  %d", i, x);
            if(x = 1)
            {
                printf("%d\n", i);
            }
        }
    }
        return (0);
}

/**
 *
 *returns 1 if b is prime else returns 0
 */

int isprime(int b)
{
    int x, count = 0;
    printf("input recieved %d \n", b);
    for(x = 1; x <= b;  x++)
    {
        if (b % x == 0)
        {
            count = count + 1;
        }
        printf("the value of count is %d\n", count);
    }
    if(count == 2) {
        printf("returning the value as 1\n");
        return 1;
    }
    else {
        printf("returning the value as 0\n");
        return 0;
    }
}

2 个答案:

答案 0 :(得分:4)

if(x = 1)

=是作业。您需要==运算符。你在其他if条件下做得正确。

此外,计算素数的逻辑是低效的。一旦计数大于2,您就可以打破循环。

if (b % x == 0)
{
    count = count + 1;
    if (count > 2)
    {
       // This ensures you are returning correct value later.
       break;
    }
}

看看这个算法:Sieve of Eratosthenes

答案 1 :(得分:0)

这个答案是对的。

为了消除这种错误,请使用

if(1=x)

使用这种方法可以避免这种行为。

这里我只是为了避免拼写错误。

相关问题