做题时只提交核心函数的代码即可
// 核心函数的实现
#include <stdbool.h> // 库函数,里面有bool类型
bool IsPerfectSquare(const int n)
{
if ((int)sqrt(n) * (int)sqrt(n) == n) // 判断是否为完全平方数
{
return true;
}
return false;
}
bool SameDigitExist(const int n)
{
int digits[10] = {0}; // 保持初始化变量的编程习惯
int tmpNum = n; // 同上
do
{
++digits[tmpNum % 10]; // 计算每个数字出现的次数
tmpNum /= 10; // 除以10,去掉最后一位
} while (tmpNum > 0);
for (int idx = 0; idx < 10; ++idx) // 遍历数组
{
if (digits[idx] > 1)
{
return true; // 如果有数字出现次数大于1,则返回true
}
}
return false; // 否则返回false
}
int IsTheNumber(const int N)
{
if ((IsPerfectSquare(N)) && (SameDigitExist(N))) // 判断是否为完全平方数且有相同的数字
{
return 1; // 是则返回1
}
return 0; // 否则返回0
}
本题要求实现一个函数,判断任一给定整数N
是否满足条件:它是完全平方数,又至少有两位数字相同,如144
、676
等。
函数接口定义:
int IsTheNumber ( const int N );
其中N
是用户传入的参数。如果N
满足条件,则该函数必须返回1
,否则返回0
。
下面是完整的可执行代码(可以直接在本地编译并运行):
#include <stdio.h> // 编译预处理语句
#include <math.h> // 库函数,里面有sqrt函数
int IsTheNumber(const int N);
int main(void) // 主函数
{
int n1 = 0; // 保持初始化变量的编程习惯
int n2 = 0; // 同上
int cnt = 0;
scanf("%d %d", &n1, &n2);
for (int idx = n1; idx <= n2; ++idx)
{
if (IsTheNumber(idx))
{
cnt++;
}
}
printf("cnt = %d\n", cnt);
return 0;
}
// 核心函数的实现
#include <stdbool.h> // 库函数,里面有bool类型
bool IsPerfectSquare(const int n)
{
if ((int)sqrt(n) * (int)sqrt(n) == n) // 判断是否为完全平方数
{
return true;
}
return false;
}
bool SameDigitExist(const int n)
{
int digits[10] = {0}; // 保持初始化变量的编程习惯
int tmpNum = n; // 同上
do
{
++digits[tmpNum % 10]; // 计算每个数字出现的次数
tmpNum /= 10; // 除以10,去掉最后一位
} while (tmpNum > 0);
for (int idx = 0; idx < 10; ++idx) // 遍历数组
{
if (digits[idx] > 1)
{
return true; // 如果有数字出现次数大于1,则返回true
}
}
return false; // 否则返回false
}
int IsTheNumber(const int N)
{
if ((IsPerfectSquare(N)) && (SameDigitExist(N))) // 判断是否为完全平方数且有相同的数字
{
return 1; // 是则返回1
}
return 0; // 否则返回0
}
输入样例:
105 500
输出样例:
cnt = 6