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值!