简体   繁体   English

为什么我的用户定义函数的return语句在某些情况下不起作用?

[英]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. 我的素数检查功能显示9,15等不是素数。 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: 当我输入9时,程序显示如下:

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 ; 您需要检查对prime_function的递归调用的返回值; at the moment its return value is being ignored and the function will return true in cases when it shouldn't. 目前,它的返回值被忽略,如果不需要,该函数将返回true。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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