gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:33:01 24 4
gpt4 key购买 nike

我从函数 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;
}
}

最佳答案

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

关于c - 从函数返回的值与接收到的值不同。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18676263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com