C ++返回值类型(整数)与函数类型不匹配

时间:2020-06-21 05:47:02

标签: c++ function return-type

#include <iostream>
#include <ctime>
using namespace std;


void randNum()
{
    int num1 = (rand() % 12) + 1;
    int num2 = (rand() % 12) + 1;
    int answer;
    answer = num1 * num2;

    return answer, num1, num2;
}
int main()
{
    srand(time(NULL));
}

我得到错误返回值类型与函数类型不匹配。答案是整数,但是无论如何它都不会返回。

3 个答案:

答案 0 :(得分:2)

您不能退回3件东西。如果愿意,可以将其包装在结构中。并使函数返回结构而不是void。在主要方面,调用您的函数

#include <iostream>
#include <ctime>
using namespace std;


struct three_values {
    int a;
    int b;
    int c;
};

three_values randNum()
{
    three_values return_me;
    int num1 = (rand() % 12) + 1;
    int num2 = (rand() % 12) + 1;
    int answer;
    answer = num1 * num2;
    return_me.a = num1;
    return_me.b = num2;
    return_me.c = answer;
    return return_me;
}

int main()
{
    srand(time(NULL));
    three_values var = randNum();

    std::cout << "num_1 = " << var.a << ", " << "num_2 = " << var.b << std::endl;
    std::cout << var.a << "*" << var.b << " = " << var.c << std::endl;
}

可能的输出:

num_1 = 6, num_2 = 7                                                         
6*7 = 42  

答案 1 :(得分:1)

您的函数被声明为返回void,在C ++中,这意味着它不返回任何内容。 您首先需要将函数签名返回类型更改为计划返回的类型(例如int)。

此外,正如已经写过的-在C ++中,您无法像在Python中那样返回多个变量。您可以通过函数参数中的引用或指针或包含所有这些值的结构的返回值来传回值。

答案 2 :(得分:0)

看看您的代码!您正在尝试从 void 函数返回一个值并返回多个值。这是完全错误的。而不是无效randNum() 您应该使用 int randNum() 。并只返回答案。

这是正确的代码>>

#include <iostream>
#include <ctime>
using namespace std;


int randNum()
{
    int num1 = (rand() % 12) + 1;
    int num2 = (rand() % 12) + 1;
    int answer;
    answer = num1 * num2;

    return answer;
}
int main()
{
    srand(time(NULL));
}