简体   繁体   中英

compiling my simple C code

Whenever I try to compile the following code, I can enter the initial value I ask for but then nothing happens. Also, there is no build error that being picked up so i don't know why this is happening. Please help and thank you in advance.

#include <stdio.h>
#include <stdbool.h>
int n;
int allDaPrimes[1000];
int counter = 0;
bool isPrime(int number);
int i;

int main()
{
    printf("Please enter a numeric value now: ");
    scanf("%d", &n);
    for (i = 2; i <n; i++){
        isPrime(i);
        if(isPrime(i)) {
            allDaPrimes[counter] = i;
            counter++;
        }
        }


    for(i= 0; i==counter; i++){
        printf("%d", allDaPrimes[i]);
    }
    return 0;

   }

bool isPrime(int number) {
    for (i= 2; i <= number; i++){
        if(number % i == 0 && number != i){
            return false;
        }

    }
    return true;
}

This is a logic error in your code, which means your code is doing exactly what you told it to, but it's not what you had in mind in your head.

The problem is this statement

for(i= 0; i==counter; i++){
    printf("%d", allDaPrimes[i]);
}

It starts with i=0 then runs while i==counter, which is probably not what you had in mind. You probably meant: i<counter

All your variables are declared globally rather than locally in the functions where they are used. This means that you're getting conflicts between the different functions.

Take i for example. In the loop in main , you start off with it set to 2. But isPrime() changes it to be n+1 because that is the last value it'll be after the loop in there finishes. But you call that twice so i ends up being n+2 , so the main loop only runs once. And if you end up with any values in the array, it'll be n+2 if n+1 was a prime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM