黎子卿 发表于 2023-11-5 18:16:30

这个求最大值的代码为什么不对

#include <iostream>
#include <vector>
using namespace std;
int max(int x,vector<int> n)
{
        if (n.size() == 1)
        {
                return n;
        }
        vector<int> new1(n.begin() + 1, n.end());
        return max(n,new1 );
       
}
int main()
{
        int n;
        cin >> n;
        int num;
        vector<int> nums;
        for (int i = 1; i <= n; i++)
        {
                cin >> num;
                nums.push_back(num);
        }
        cout << max(-2147483648, nums);
        return 0;
}

isdkz 发表于 2023-11-5 18:16:59

这个代码中的问题在于递归调用的时候没有正确地更新传递给函数的向量参数。在函数的递归调用中,应该传递新的向量new1,而不是原始向量n。所以,将代码中的 return max(n,new1 ); 改为 return max(x, new1); 即可解决问题。

修改后的代码如下:

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

int max(int x, vector<int> n)
{
    if (n.size() == 1)
    {
      return n;
    }
    vector<int> new1(n.begin() + 1, n.end());
    return max(x, new1);
}

int main()
{
    int n;
    cin >> n;
    int num;
    vector<int> nums;
    for (int i = 1; i <= n; i++)
    {
      cin >> num;
      nums.push_back(num);
    }
    cout << max(-2147483648, nums);
    return 0;
}


这样修改后的代码就能正确地求出向量中的最大值了。

Mike_python小 发表于 2023-11-5 18:17:13

这段代码存在一个问题,即在递归调用max函数时传递的参数有误。

在函数定义中,max函数的第一个参数是一个整数 x,第二个参数是一个整数向量 n。然而,在递归调用的语句 return max(n, new1); 中,第一个参数使用的是 n,而应该是 x。

为了修正这个问题,你需要将递归调用的语句修改为 return max(x, new1);。这样,递归调用时会将正确的参数传递给max函数。

以下是修改后的代码:


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

int max(int x, vector<int> n)
{
    if (n.size() == 1)
    {
      return n;
    }
    vector<int> new1(n.begin() + 1, n.end());
    return max(x, new1);
}

int main()
{
    int n;
    cin >> n;
    int num;
    vector<int> nums;
    for (int i = 1; i <= n; i++)
    {
      cin >> num;
      nums.push_back(num);
    }
    cout << max(-2147483648, nums);
    return 0;
}


请注意,为了避免与 C++ 标准库的 std::max 函数冲突,我将函数名修改为 max。这样可以确保代码能够正常编译和运行。

希望这可以解决你的问题。如果你还有其他疑问,请随时提问。

球一个最佳答案谢谢啦!这对我非常重要!{:10_254:}{:10_254:}{:10_254:}
页: [1]
查看完整版本: 这个求最大值的代码为什么不对