gpt4 book ai didi

C 程序不给出素数

转载 作者:行者123 更新时间:2023-11-30 19:34:05 25 4
gpt4 key购买 nike

我已经在 Ubuntu Mate 中安装了 Eclipse。当我编译以下程序时,它编译它而没有给出任何错误。它在 Eclipse 文本编辑器窗口中没有显示任何警告或错误,但是当我编译它时,它显示“所需项目中存在错误。继续启动吗?”。

这是我的代码:

#include <stdio.h>
int main(){
int a,b,num,div,exi;
printf("this program find out the prime numbers\nnow enter the number until you want to find prime numbers here:- ");
scanf("%d",&b);


for(num=1;num<=b;num++)
{
for(div=2;div<=(num/2);div++)
{
a=num%div;
if(a!=0)
{
continue;
}
else
{
printf("%d \n",num);
break;
}
}
}



printf("enter any digit to exit");
scanf("%d",&exi);
printf("you entered the %d,thus good bye",exi);
}

当我点击"is"按钮时,它会给出以下输出:

this program find out the prime numbers
now enter the number until you want to find prime numbers here:- 20
4
6
8
9
10
12
14
15
16
18
20
enter any digit to exit7
you entered the 7,thus good bye

这不是我想要的输出,但是 Eclipse 没有告诉我程序中的错误是什么,以便我可以修复它。另外,你能告诉我我的代码有什么问题吗?

最佳答案

Eclipse 无法告诉您您的程序无法运行。它只能告诉您您的代码是否无法编译成程序。

您的代码可以编译,因此 Eclipse 不会给出任何错误。

但是你的程序无法工作,因为它不打印素数。

让我们看看你的内循环:

  for(div=2;div<=(num/2);div++) // Here you want to test if num can be divided
// by 2 or 3 or 4 or .....
// That is fine
{
a=num%div; // So here you do the check, i.e. you calculate
// the reminder
if(a!=0)
{
// Reminder is non-zero. That will happen for e.g. 5%2 (which is 1)
// So you continue the loop if num is a prime candidate
continue;
}
else
{
// Reminder is zero. That will happen for e.g. 4%2
// So you print the numbers that are NOT primes and stop the loop
printf("%d \n",num);
break;
}
}

所以最后,你的程序做了与你想要的相反的事情。它打印所有非素数并忽略素数。

所以切换就在你检查完所有值之前不要打印!因此 - 在内部循环中使用标志并在外部循环中打印。

类似于:

#include <stdio.h>
int main()
{
int a,b,num,div,exi;
printf("this program find out the prime numbers\nnow enter the number until you want to find prime numbers here:- ");
scanf("%d",&b);


for(num=2;num<=b;num++) // Start from 2
{
int flag = 1; // Assume prime
for(div=2;div<=(num/2);div++)
{
a=num%div;
if(a==0)
{
flag = 0; // No - not a prime
break;
}
}
if (flag) // Was it a prime?
{
printf("%d \n",num); // Yes
}
}



printf("enter any digit to exit");
scanf("%d",&exi);
printf("you entered the %d,thus good bye",exi);
}

注意:我尝试使此答案中的代码与问题中的代码相似。但是,可以通过多种方式提高代码的性能。只需在 SO 上搜索“prime”,您就会找到更多最佳解决方案。

关于C 程序不给出素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44344113/

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