确定数字是否为素数。 使用Codeblocks 13.12执行。 编译器GNU GCC 4.7.0
#include <stdio.h>
main()
{
int input,check,count;
printf("Enter the number: ");
scanf("&d",&check);
count=0;
for(check=1;check<=1;check++)
{
if((input%check)==0)
{
count++;
}
}
if(count==2)
{
printf("The number %d is prime",check);
}
else
{
printf("The number %d is not prime",check);
}
}
请注意,没有错误或警告。 但是,即使在给出其他输入之后,编译器也假定数字为“2”,并且它表示2不是素数!!
答案 0 :(得分:2)
scanf("&d",&check);
应该是
// v-- percent, not ampersand
scanf("%d",&check);
或(可能)
scanf("%d", &input);
...因为阅读input
变量会更有意义。然后,在该计划的后期,
printf("The number %d is prime", check);
应该是
printf("The number %d is prime\n", input);
因为您正在检查input
,而不是check
。那下面两行相同。最后,
for(check=1;check<=1;check++)
毫无意义。循环只运行一次,你不想测试输入是否可以被1整除。这将是有意义的
// v-- check factors until input
for(check=1;check<=input;check++)
这不是最有效的检查,但它可以帮助您入门。
旁注:原型
main()
仅符合C89。从C99开始,不再包括旧的K&amp; R函数声明方法,并且main的正确等效原型是
int main(void)
所以,当你正在修理东西时,你应该把它放在那里。
答案 1 :(得分:0)
有些问题是:
input
。 for(check=1;check<=1;check++)
这似乎不正确,只对所有情况循环一次。 %d
而不是&d
传递,使用scanf读取值。 答案 2 :(得分:0)
嗯,我认为总是归结为有人在为提问者编写代码。
#include <stdio.h>
#include <conio.h>
int main() // note "int" before "main()"
{
int input, check, count;
printf("Enter the number: ");
scanf("%d", &input); //I believe this is what you meant instead of storing the inputted value in "check"
count = 0;
check = 2; //Check should equal "2" because anything divided by one will have no remainder
while((count != 1) && (check <= 50)) //If you want to stop trying to divide when the number you're dividing by is above 50, change this line. I stopped at 50 just as a random number, but I'm sure there's a more logical one to use. ------ "while(count != 1)" stops the loop when the number is successfully divided.
{
if (check == input) break; // stop checking when the number we're trying to divide is equal to the number to divide by.
if((input%check) == 0)
{
count++;
}
check++; //increment the number we're checking by
}
if(count == 1)
{
printf("The number %d is not prime\n", input); // output the number the user tried to input
}
else
{
printf("The number %d is prime\n", input);
}
getch();
return 1;
}
我求求你阅读这些评论并理解它们,而不仅仅是复制代码,正如我多次看到的那样。
编辑:我最初错误包括c ++函数。它现在在C中。