为什么我的用户定义函数的 return 语句在某些情况下不起作用?
Why a return statement of my user defined function doesn't work at some case?
我的质数检查函数显示 9,15 等为质数,而它们不是。我的代码是:
#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;
}
我使代码非常图形化,以便可以轻松找到错误。当我输入 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.
它应该打印一次"Going to main function."然后进入主函数。但它并没有,它遍历了整个函数,然后进入了 main 函数。谁能帮我解决这个问题?
而不是
prime_function(num,++i);
你想要
return prime_function(num,++i);
您需要检查对 prime_function
的递归调用的 return 值;目前它的 return 值被忽略,并且函数将 return 在不应该的情况下为真。
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;
}
我的质数检查函数显示 9,15 等为质数,而它们不是。我的代码是:
#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;
}
我使代码非常图形化,以便可以轻松找到错误。当我输入 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.
它应该打印一次"Going to main function."然后进入主函数。但它并没有,它遍历了整个函数,然后进入了 main 函数。谁能帮我解决这个问题?
而不是
prime_function(num,++i);
你想要
return prime_function(num,++i);
您需要检查对 prime_function
的递归调用的 return 值;目前它的 return 值被忽略,并且函数将 return 在不应该的情况下为真。
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;
}