第7章 指针 第5题

题目:

编写一个函数,判断作为参数传入的一个整型数组是否为回文。例如,若数组元素值为10、5、30、67、30、5、10就是一个回文。

代码:

#include <iostream>
using namespace std;

bool 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) == true) cout << "此数组的内容是回文";
	else cout << "此数组的内容不是回文";
	cout << endl << endl;

	system("pause");
	return 0;
}

bool 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 true;
	else return false;
}

猜你喜欢

转载自blog.csdn.net/weixin_41013202/article/details/79803742
今日推荐