简体   繁体   中英

Why a return statement of my user defined function doesn't work at some case?

A prime checking function of mine shows 9,15 etc as prime where they aren't. My code is :

#include<iostream>
#include<cstdio>
using namespace std;
int prime_function(int num, int i);
int main(){
    int num,flag=0;
    while (cin>>num){
        if(num!=1){
            flag=prime_function(num,2);
            if(flag==0)
                printf("%d isn't a prime.\n",num);
            else {
                printf("%d is a prime.\n",num);
            }   
        }
        else {
            printf("%d is a prime.\n",num);
        }
    }
    return 0;
}

int prime_function(int num, int i)
{
    if(num%i==0){
        printf("when num mod i == 0, num=%d    i=%d\n",num,i);
        return 0;//This Statement doesn't work for like num=9,15...
    }
    else if((i*i)+1<=num){
        printf("when num mod i != 0, num=%d    i=%d\n",num,i);
        prime_function(num,++i);
    }
    printf("Going to main function.\n");
    return 1;
}

I made the code pretty much graphical so that errors can be found easily. When I input 9 my program shows like:

when num mod i != 0, num=9    i=2
when num mod i == 0, num=9    i=3
Going to main function.
Going to main function.
9 is a prime.

It should print "Going to main function." once and then come to main function. But it doesn't and goes through the entire function and then comes to main function. Can anyone help me with this problem?

Instead of

prime_function(num,++i);

You want

return prime_function(num,++i);

You need to check the return value of your recursive call to prime_function ; at the moment its return value is being ignored and the function will return true in cases when it shouldn't.

else if((i*i)+1<=num){
    printf("when num mod i != 0, num=%d    i=%d\n",num,i);
    if (!prime_function(num,++i))
         return 0;
}

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