如何通过将其元素放入c中的不同子集来组织数组?

我想通过将素数放入一个子集来组织一组整数.

例如:

输入集:
{} 2,4,6,7,11,6,3.

期望的结果:

素数:{2,7,11,3}.

非素数:{4,6,6}.

这是我合理的代码,结果是一个荒谬的结果:

#include <stdio.h>
 int main() {
 int i,j,n,a=0,b1=0,b2=0;
 printf(" Enter the number of elements in the set: ");
 scanf("%d",&n);
 int integer[n],nonPrime[n],prime[n];
 for(i=1;i<=n;i++) {
     printf(" Enter #%d element of the set: ",i);
     scanf("%d",&integer[i-1]);
 }
 printf("\n The set is: {");
 for(i=1;i<=n;i++) {
     printf("%d ",integer[i-1]);
 }
 printf("}");
 for(i=1;i<=n;i++) {
     for(j=2;j<=integer[i-1]/2;j++) {
         if(integer[i-1]%j==0) {
             a=1;
             break;
         }
     }
     if(a==1) {
         integer[i-1]=nonPrime[i-1];
         b1++;

     }
     else {
         integer[i-1]=prime[i-1];
         b2++;

     }
 }
 printf("\n Prime numbers: { ");
 for(i=1;i<=b2;i++) {
     printf("%d ",prime[i-1]);
 }
 printf("}\n Non prime numbers: { ");
 for(i=1;i<=b1;i++) {
     printf("%d ",nonPrime[i-1]);
 }
 printf("} \n");

return 0;
}
 //HENG SOK MENG

输出:

 Enter the number of elements in the set: 6
 Enter #1 element of the set: 1
 Enter #2 element of the set: 3
 Enter #3 element of the set: 5
 Enter #4 element of the set: 7
 Enter #5 element of the set: 4
 Enter #6 element of the set: 6

 The set is: {1 3 5 7 4 6 }
 Prime numbers: { 1965421290 1965972381 718360966 32 }
 Non prime numbers: { 2686560 718361022 }

 Process returned 0 (0x0)   execution time : 6.063 s
 Press any key to continue.

最佳答案 我认为你的逻辑有些错误.此代码显示您的循环可以简化为(i = 0; i< n; i),这将允许索引[i]而不是[i-1]. 您可以使用像isprime(int n)这样的辅助函数来检查整数[n]数组中的素数,然后相应地添加到其他相应的分区数组. 此代码段演示了这一点:

#include <stdio.h>
#include <stdlib.h>

int isprime(int n);

int 
main(void) {
    int n, i, primecnt = 0, nonprimecnt = 0;

    printf("Enter the number of elements in the set: ");
    if (scanf("%d", &n) != 1) {
        printf("Invalid entry\n");
        exit(EXIT_FAILURE);
    }

    int integers[n], prime[n], nonprime[n];

    for (i = 0; i < n; i++) {
        printf(" Enter #%d element of the set: ",i+1);
        if (scanf("%d", &integers[i]) != 1) {
            printf("Invalid entry\n");
            exit(EXIT_FAILURE);
        }
    }

    printf("\n The set is: {");
    for(i = 0;i < n; i++) {
        printf("%d ",integers[i]);
    }
    printf("}");

    for (i = 0; i < n; i++) {
        if (isprime(integers[i])) {
            prime[primecnt++] = integers[i];
        } else {
            nonprime[nonprimecnt++] = integers[i];
        }
    }

    printf("\n Prime numbers: { ");
    for(i = 0; i < primecnt; i++) {
        printf("%d ", prime[i]);
    }
    printf("}\n Non prime numbers: { ");
    for(i = 0; i < nonprimecnt; i++) {
        printf("%d ",nonprime[i]);
    }
    printf("} \n");

    return 0;
}

int
isprime(int n) {
    int divisor;
    if (n < 2) {
        return 0;
    }

    for (divisor=2; divisor*divisor<=n; divisor++) {
        if (n%divisor==0) {
            return 0;
        }
    }
    return 1;
}
点赞