大家好,我需要编写一个程序,要求用户输入数字作为参数,然后让他们知道它是质数还是否则为0。因此,到目前为止,我的代码如下,但我对如何使其运行于的所有可能值并确保其不是非素数感到有些困惑。现在发生的事情是程序打开,我输入了一个值,什么也没有发生。注意:标头中有数学运算,因为我不确定在此阶段是否需要它。
编辑:因此,我对建议进行了更改,并且还对循环进行了补充,无论我何时编译程序,我都会得到“控制可能会达到无效功能”的警告。当我输入一个数字然后直接输入一个无关紧要的程序时,无论该程序如何编译,无论是不是一个原始数字,我都说“浮点异常:8”时出现错误。
编辑2:浮点错误已得到解决,但是现在程序集认为每个数字都是非主要的,并以此方式进行输出。我无法看到为什么要这么做。我也仍然会收到“控制权可能会达到无效功能的警告”警告
#include <stdio.h>
#include <math.h>
int prime(int a){
int b;
for(b=1; b<=a; b++){
if (a%b==0)
return(0);
}
if(b==a){
return(1);
}
}
int main(void){
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1){
printf("%d is a prime number \n",c);
}
else
printf("%d is not a prime number\n",c);
}
最佳答案
我刚刚修改了您的功能。这是代码
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b=2,n=0;
for(b=2; b<a; b++)
{
if (a%b==0)
{
n++;
break;
}
}
return(n);
}
int main(void)
{
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1)
{
printf("%d is not a prime number \n",c);
}
else
{
printf("%d is a prime number\n",c);
}
return 0;
}
说明-
在for循环中,我从2开始,因为,我想查看给定的数字是否可以被2整除或大于2的数字。而且我使用过break,因为一旦数字可被整除,我就不想再检查一次。因此,它将退出循环。
在您的主要功能中,您没有为printf()语句正确分配。如果answer == 1,则它不是质数。 (因为这意味着一个数字可以被其他数字整除)。您写的是素数(错了)。
如果您有任何疑问,请让我听听。
关于c - C程序查找素数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32649594/