如何将'int'函数调用到'void'函数

how to call a 'int' function to a 'void' function

本文关键字:void 函数 函数调用 int      更新时间:2023-10-16

我试图根据使用2个不同的函数的返回值打印某个消息。当在内部调用函数时,另一个则表示没有声明

int isMatch(int x1, int y1, int x2, int y2)
{
    if(deck[x1][y1] == deck[x2][y2])
    {
        return 2;
    }
    else if(deck[x1][y1][0] == deck[x2][y2][0])
    {
        return 1;
    }
    else if(deck[x1][y1][1] == deck[x2][y2][1])
    {
        return 1;
    }
    return 0;
}
void printMatch()
{
    int attempt;
    isMatch(x1, y1, x2, y2);
    if(isMatch() == 2)
    {
        cout << "You have a match!";
        attempt++;
    }
}

当我这样尝试时,它仍然不起作用

int isMatch(int x1, int y1, int x2, int y2)
{
    if(deck[x1][y1] == deck[x2][y2])
    {
        return 2;
    }
    else if(deck[x1][y1][0] == deck[x2][y2][0])
    {
        return 1;
    }
    else if(deck[x1][y1][1] == deck[x2][y2][1])
    {
        return 1;
    }
    return 0;
}
void printMatch()
{
    int attempt;
    int isMatch(int x1, int y1, int x2, int y2);
    if(isMatch() == 2)
    {
        cout << "You have a match!";
        attempt++;
    }
}

!!!!!!!!!!更新 !!!!!!!!!!!!!!!!!

int isMatch(int x1, int y1, int x2, int y2)
{
    if(deck[x1][y1] == deck[x2][y2]) /// Checks entire element (_,_)
    {
        return 2;
    }
    else if(deck[x1][y1][0] == deck[x2][y2][0]) /// Checks first element (_, )
    {
        return 1;
    }
    else if(deck[x1][y1][1] == deck[x2][y2][1]) /// Checks second element ( ,_)
    {
        return 1;
    }
    return 0;
}
void printMatch()
{
    int attempt = 0; /// increments the users attempts
    int score = 0; /// adds total score
    int x1 = 0, y1 = 0, x2 = 0, y2 = 0;
    int match = isMatch(x1, y1, x2, y2);
    if (match == 2)
    {
        attempt++;
        score = score + 2;
        cout << "nYou have a match!"
             << "nTotal score is: " << score
             << "nTotal no. of attempts: " << attempt << endl << endl;
    }
    else if (match == 1)
    {
        attempt++;
        score = score + 1;
        cout << "nYou have a match!"
             << "nTotal score is: " << score
             << "nTotal no. of attempts: " << attempt << endl << endl;
    }
}

将printMatch()函数更改为:

void printMatch(int x1, int y1, int x2, int y2)
{
    int attempt;
    int temp = isMatch(x1, y1, x2, y2);
    if(temp == 2)
    {
        cout << "You have a match!";
        attempt++;
    }
}

这将isMatch函数的返回值保存到名为temp的变量中。然后,您可以使用这个变量temp来测试您的条件。

您的printMatch函数存在许多问题。试一试

void printMatch()
{
    int x1 = 4, y1 = 3, x2 = 2, y1 = 1; //you'll need to define these values in some useful way
    int attempt = 0;
    int match = isMatch(x1, y1, x2, y2);
    if(match == 2)
    {
        cout << "You have a match!";
        attempt++;
    }
}