在这段代码中,你键入一个数字,然后通过返回0或1告诉你它是否为素数。然后它应该打印数组'prime'的0或1项。但是,我遇到了这个问题,我不知道如何解决列表问题。 (我对C来说是全新的)
#include <stdio.h>
#include <string.h>
int test(int number) { /*1 means prime, 0 means not*/
int iter;
int mod;
if (number == 1) {
return 0;
}
for (iter=2;iter<number-1;iter+=1) {
if (number % iter == 0){
return 0;
}
}
return 1;
}
int main(){
char prime[2] = {'This number isn\'t prime','This number is prime'};
int userIn;
printf("Enter an integer to check: ");
scanf("%d",userIn);
printf("%c",prime[test(userIn)]);
}
答案 0 :(得分:0)
我添加了函数声明和printf。
#include <stdio.h>
int primeNumber(int number); //function declaration
int main() {
int userIn;
printf("Enter an integer to check: ");
scanf("%d",&userIn);
if(primeNumber(userIn) == 0) {
printf("This number isn\'t prime");
} else {
printf("This number is prime");
}
return 0;
}
int primeNumber(int number) {
int iter;
if (number == 1 || number < 0) {
return 0;
}
for (iter = 2; iter < number - 1; iter += 1) {
if (number % iter == 0){
return 0;
}
}
return 1;
}
答案 1 :(得分:-1)
bool IsPrime (int number) { // Make your function names more descriptive...
int iter;
// int mod; ...and remove superfluous variables
if (number < 1) {
return false;
}
// There are further possibilities for improvement here...
for (iter = 2; iter < number - 1; iter += 1) {
if (number % iter == 0) {
return false;
}
}
return true;
}
int main(int argc, char *argv[])
{
const char* outcomes[2] = { "This number isn't prime", "This number is prime" };
int input;
printf("Enter an integer to check: ");
scanf("%d", &input); // Note that scanf requires pointer to input!
printf("%s", outcomes[IsPrime(input)]);
return 0;
}