我编写了一个程序来查找少于用户输入整数的所有素数。然而,它只是挂起。我假设继续使用所有这些仍然是一团糟,我已经制作了意大利面条代码......任何人都可以帮助我吗?
/*takes integer input, displays all primes less than that integer*/
#include <stdio.h>
int main(void) {
unsigned int num_in, test_num = 0, divisor = 0;
_Bool primestate = 0;
printf("Please enter an integer.\n");
scanf("%d", &num_in);
while(test_num < num_in) {
while(divisor < test_num) {
if(test_num % divisor == 0) {
primestate = 1;
}
test_num++;
}
if(primestate == 1) {
printf("%d is prime and less than %d.\n", test_num, num_in);
} else {
continue;
}
}
return 0;
}
答案 0 :(得分:6)
您永远不会增加test_num
或divisor
,因此会卡在其中一个循环中。
while(test_num < num_in) {
while(divisor < test_num) {
if(test_num % divisor == 0) {
primestate = 1;
}
divisor++; // NEW LINE
}
if(primestate == 1) {
printf("%d is prime and less than %d.\n", test_num, num_in);
} else {
continue;
}
test_num++; // NEW LINE
}
此行上你可能除以0(当divisor
等于0时):
if(test_num % divisor == 0) {
答案 1 :(得分:0)
#include <stdio.h>
#include <stdbool.h>
int main(void) {
unsigned int num_in, test_num, divisor;
bool primestate;
printf("Please enter an integer.\n");
scanf("%u", &num_in);
if(2 < num_in)
printf("\n%u\n", 2);
for(test_num = 3; test_num < num_in; test_num += 2){
primestate = true;
for(divisor=3; divisor * divisor <= test_num ; divisor += 2) {
if(test_num % divisor == 0) {
primestate = false;
break;
}
}
if(primestate) {
printf("%u\n", test_num);
}
}
return 0;
}