B. 求最大值最小值(引用)

本文介绍如何使用C++编写函数find,通过引用操作找到数组中最小值和最大值的下标。函数通过遍历数组并更新minIndex和maxIndex,适用于动态分配的整数数组。实例代码和样例测试用例展示了如何调用该函数并输出结果。
摘要由CSDN通过智能技术生成
B. 求最大值最小值(引用)
题目描述

编写函数void find(int *num,int n,int &minIndex,int &maxIndex),求数组num(元素为num[0],num[1],...,num[n-1])中取最小值、最大值的元素下标minIndex,maxIndex(若有相同最值,取第一个出现的下标。)

输入n,动态分配n个整数空间,输入n个整数,调用该函数求数组的最小值、最大值下标。最后按样例格式输出结果。

改变函数find功能不计分。


输入

测试次数

每组测试数据一行:数据个数n,后跟n个整数


输出

每组测试数据输出两行,分别是最小值、最大值及其下标。具体格式见样例。多组测试数据之间以空行分隔。


输入样例1
2
5 10 20 40 -100 0
10 23 12 -32 4 6 230 100 90 -120 15
输出样例1
min=-100 minindex=3
max=40 maxindex=2

min=-120 minindex=8
max=230 maxindex=5

该题考察对C++引用的使用,比较简单,下面看代码

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include <iomanip>
#include<cmath>
#include<cstring>
#include<cctype>
#include<queue>
using namespace std;
int maxn = -10000, minn = 10000;
void find(int* num, int n, int& minIndex, int& maxIndex)
{
	for (int i = 0; i < n; i++)
	{
		if (num[i] > maxn)
		{
			maxn = num[i];
			maxIndex = i;
		}
		if (num[i] < minn)
		{
			minn = num[i];
			minIndex = i;
		}
	}
}
int main()
{
	int t,n,minindex=0,maxindex=0;
	cin >> t;
	while (t--)
	{
		cin >> n;
		int* num = new int[n];
		for (int i = 0; i < n; i++)
		{
			cin >> num[i];
		}
		find(num, n, minindex, maxindex);
		cout << "min=" << num[minindex] << ' ' << "minindex=" << minindex << endl;
		cout << "max=" << num[maxindex] << ' ' << "maxindex=" << maxindex << endl;
		cout << endl;
    	delete[]num;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZZZWWWFFF_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值