本题要求实现一个函数,判断任一给定整数N
是否满足条件:它是完全平方数,又至少有两位数字相同,如144、676等。
函数接口定义:
int IsTheNumber ( const int N );
其中N
是用户传入的参数。如果N
满足条件,则该函数必须返回1,否则返回0。
裁判测试程序样例:
#include <stdio.h>
#include <math.h>
int IsTheNumber ( const int N );
int main()
{
int n1, n2, i, cnt;
scanf("%d %d", &n1, &n2);
cnt = 0;
for ( i=n1; i<=n2; i++ ) {
if ( IsTheNumber(i) )
cnt++;
}
printf("cnt = %d\n", cnt);
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
105 500
输出样例:
cnt = 6
int IsTheNumber ( const int N )
{
int num[10];
int i=0,j=0,len;
int n=N;
double temp;
while(n!=0)
{
num[i]=n%10;
n/=10;
i++;
}
len = i;
n = N;
temp = sqrt(n);
if(n == (int)temp*temp)
//if(n%(int)(sqrt(n)) == 0)//错误写法
{
for(i=0;i<len;i++)
{
for(j=i+1;j<len;j++)
{
if(num[i] == num[j])
return 1;
}
}
return 0;
}
return 0;
}
注意
15、16行写法:对n开平方,若n为完全平方数,则开方后temp的小数部分全为0,再对temp平方后得到的数的小数部分也全为0,强制转化类型后应与n相等。若n不为完全平方数,则开方后temp为无限不循环小数,但返回的类型double最多只能保留15位小数,此时对temp平方后得到的数一定是小于n的,强制转换后结果为n-1。
本文链接:https://shengto.top/c/pat_39.html
转载时须注明出处及本声明