gpt4 book ai didi

c - 为什么我们在这里使用 bool ?

转载 作者:行者123 更新时间:2023-11-30 21:38:12 26 4
gpt4 key购买 nike

我不明白为什么我们使用 bool isPrime在这里,以及这个函数的作用。

{
bool isPrime;
int startingPoint, candidate, last, i;

startingPoint = 856;
if ( startingPoint < 2 )
{
candidate = 2;
}
else
if ( startingPoint == 2 )
{
candidate = 3;
}
else
{
candidate = startingPoint;
if ( candidate % 2 == 0 )
candidate--;
do
{
isPrime = true;
candidate += 2;
last = sqrt( candidate );
for ( i = 3; (i <= last) && isPrime; i += 2 )
{
if ( (candidate % i) == 0 )
isPrime = false;
}
} while ( ! isPrime );
}

printf( "The next prime after %d is %d. Happy?\n",
startingPoint, candidate );
return 0;
}

最佳答案

该函数会告诉您最终用户输入的数字后的下一个素数。 isPrime变量充当 bool “标志”,可让您将循环内找到的条件信息传递给在循环外运行的代码。

内在for循环尝试连续奇数作为除数候选。当它找到一个除数时,它需要让外部知道除数已经找到(因此候选不是素数)的事实 do/while通过设置 isPrime 进行循环标记为false 。外循环检查该标志,并且仅当它保持 true 时才存在循环。毕竟 3..sqrt(candidate) 范围内的所有候选人已经筋疲力尽了。

关于c - 为什么我们在这里使用 bool ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17925638/

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