6-7 统计某类完全平方数(20 分)

本题要求实现一个函数,判断任一给定整数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

VS2015完整代码如下:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include <math.h>

int IsTheNumber(const int N);

int main()
{
    /*int m;
    int n;
    scanf("%d", &m);
    n = sqrt(m);
    printf("输出:%d", n);*/
    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);
    system("pause");
    return 0;
}
int IsTheNumber(const int N)
{
    int i;
        int m;
        int M;
        M = N;
    m = sqrt(M);
    if (m*m == M)
    {
        int num[10] = { 0 };
        int j;
        while (M != 0)
        {
            for (j = 0;j <= 9;j++)
            {
                if (M % 10 == j)
                {
                    num[j] = num[j] + 1;
                    if (num[j] == 2)
                    {
                        return 1;
                    }
                }
            }
            M = M / 10;
        }
        return 0;////其中此处因为当初没有return 0值导致报错!
    }
    else 
      return 0;
}
 

亮点:自写函数中设置了一个数组用来存放初始值为0值,一共10位,从个位0到9,当判断一次进位时,如果相等相应下标的数组加1,直到有2出现时表示至少有两个数位相等,此时返回1值!

扫描二维码关注公众号,回复: 2726331 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_40604313/article/details/81275729
今日推荐