第6章 函数 第27题

题目:

编写一个函数,判断作为参数传入的一个整型数组的内容是否是回文。例如,数组元素值为{1,3,6,8,6,3,1},则是一个回文。


代码:

#include <iostream>
using namespace std;

int function(int *a, int length);

int main()
{
	cout << "判断输入的一个整型数组的内容是否是回文" << endl << endl;

	int length;
	cout << "请输入数组的元素个数:";
	cin >> length;
	int *a = new int[length];
	cout << "请输入这个数组:";
	for (int i = 0; i < length; ++i) cin >> a[i];

	cout << endl;
	if (function(a, length) == 1) cout << "此数组的内容是回文";
	else cout << "此数组的内容不是回文";

	cout << endl << endl;
	system("pause");
	return 0;
}

int function(int *a, int length)
{
	int end;
	bool judge = true;
	
	if (length % 2 == 0) end = length / 2;   //数组个数为偶数
	else end = (length - 1) / 2;   //数组个数为奇数

	for (int i = 0; i < end; ++i)
	{
		if (a[i] != a[length - 1 - i]) judge = false;
	}

	if (judge == true) return 1;
	else return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值