鱼C论坛

 找回密码
 立即注册
查看: 1044|回复: 2

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

[复制链接]
发表于 2023-11-5 18:16:30 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include <iostream>
#include <vector>
using namespace std;
int max(int x,vector<int> n)
{
        if (n.size() == 1)
        {
                return n[0];
        }
        vector<int> new1(n.begin() + 1, n.end());
        return max(n[0],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;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-11-5 18:16:59 | 显示全部楼层
这个代码中的问题在于递归调用的时候没有正确地更新传递给函数的向量参数。在函数的递归调用中,应该传递新的向量new1,而不是原始向量n。所以,将代码中的 return max(n[0],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[0];
    }
    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;
}

这样修改后的代码就能正确地求出向量中的最大值了。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-11-5 18:17:13 | 显示全部楼层
这段代码存在一个问题,即在递归调用max函数时传递的参数有误。

在函数定义中,max函数的第一个参数是一个整数 x,第二个参数是一个整数向量 n。然而,在递归调用的语句 return max(n[0], new1); 中,第一个参数使用的是 n[0],而应该是 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[0];    }    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。这样可以确保代码能够正常编译和运行。

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

球一个最佳答案谢谢啦!这对我非常重要!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-5 13:23

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表