简体   繁体   English

在 C++ 中给出错误返回类型的错误

[英]Giving error for wrong return type in C++

#include<iostream>
using namespace std;

void factor(int n)
{
    if(n<=1)
    return;
    for(int i=2;i*i<=n;i++){
        while(n%i==0){
            printf(i);
            n=n/i;
        }
    }
    if(n>1)
    {
    return n;
    }
}

int main(){
    factor(10);
}

Error: return-statement with a value, in function returning 'void' [-fpermissive] 16 |错误:带有值的返回语句,在 function 返回 'void' [-fpermissive] 16 | return n;返回 n; | | ^ ^

The return type shoud not be void but int.返回类型不应该是 void 而是 int。

The problem is that your function factor has a return type of void but it actually returns an int object.问题是您的 function factor的返回类型为void ,但它实际上返回一个int object。

To solve this, you should match the return type of the function factor with what you're actually returning from inside the function as shown below.为了解决这个问题,您应该将 function factor的返回类型与您实际从 function 内部返回的类型相匹配,如下所示。

Secondly you should also take care of the situation when none of the conditions(like if ) are satisfied by adding appropriate return statements as shown below:其次,您还应该通过添加适当的返回语句来处理不满足任何条件(如if )的情况,如下所示:

int factor(int n) //VOID CHANGED TO INT HERE
{
    if(n<=1)
    return 0; //CHANGED RETURN TO RETURN 0 HERE
    for(int i=2;i*i<=n;i++){
        while(n%i==0){
            //printf(i);
            n=n/i;
        }
    }
    if(n>1)
    {
    return n;
    }
    return 0;//ADDED RETURN HERE for the case if none of the if are satisfied and control flow reaches here
}

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

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