先贴出题目
计算水仙花数
int narcissistic( int number );
void PrintN( int m, int n );
#include <stdio.h>
int narcissistic( int number );
void PrintN( int m, int n );
int main()
{
int m, n;
scanf("%d %d", &m, &n);
if ( narcissistic(m) ) printf("%d is a narcissistic number\n", m);
PrintN(m, n);
if ( narcissistic(n) ) printf("%d is a narcissistic number\n", n);
return 0;
}
/* 你的代码将被嵌在这里 */
下面是我的答案 由于题目里面没有包含MATH.H函数
所以我自己写了一个输出指数的函数;我的代码在VS2019上面调试模式找了很久都不知道为什么不能通过测试
int narcissistic(int number)
{
int a = number;
int b = number;
int leng = 0;
int sum = 0;
for (; a > 0; a /= 10)leng++;//整数的位数
a = number;
for (int c = 0; c < leng; c++) //判断水仙花数
{
b = a % zhishu(10, c);
sum = sum + zhishu(b, leng);
a /= 10;
}
if (sum == number)return 1;
return 0;
}
void PrintN(int m, int n)
{
for (int a = m + 1; a < n; a++)
{
if (narcissistic(a))printf("%d\n", a);
}
}
int zhishu(int num, int times)///输出指数
{
int a = 0;
int b = num;
for (; a < times - 1; a++)
{
b = b * num;
}
return b;
}
但是我找到的网上的答案却可以通过测试 下面是网上的代码
他使用了POW函数 但是返回了一个不正确的的值 却通过了测试
int narcissistic(int number) {
int i, n = 0, sum = 0, cnt = 0;
n = number;
while (n) {
cnt++;
n /= 10;
}
n = number;
while (n) {
i = n % 10;
sum += (int)pow(i, cnt);
n /= 10;
}
if (sum == number)
return 1;
else
return 0;
}
void PrintN(int m, int n) {
int i;
for (i = m + 1; i < n; i++)
if (narcissistic(i))
printf("%d\n", i);
}
可以看到他的SUM函数明显数值不对 但是为什么能通过测试呢