题目:
写一个函数 bool isEven(int n);,当n的每一位数都是偶数时,返回true,否则返回false。如n的值是1234,函数返回false。如n的值为2484,返回true。用递归和非递归两张方法实现。
代码:
1.非递归:
//非递归
#include <iostream>
using namespace std;
bool isEven(int n);
int main()
{
cout << "判断某个数的每一位数是否都是偶数" << endl << endl;
int n;
cout << "请输入一个数:";
cin >> n;
cout << isEven(n) << endl << endl;
system("pause");
return 0;
}
bool isEven(int n)
{
while (n != 0)
{
if ((n%10)%2!=0) return false;
n = n / 10;
}
return true;
}
2.递归:
//递归
#include <iostream>
using namespace std;
bool isEven(int n);
int main()
{
cout << "判断某个数的每一位数是否都是偶数" << endl << endl;
int n;
cout << "请输入一个数:";
cin >> n;
if (isEven(n) == 0) cout << n << "不是每一位数都是偶数" << endl << endl;
else cout << n << "的每一位数都是偶数" << endl << endl;
system("pause");
return 0;
}
bool isEven(int n)
{
if (n == 0) return 1;
if ((n % 10) % 2 == 0) isEven(n / 10);
else return 0;
}