int sign(int x)
{
if (x > 0)
return 1;
else if (x == 0)
return 0;
else
return -1;
}
6-2 求排列数
c复制代码
double fact(int n)
{
long long ret = 1;
for (long long i = 1; i <= n; i++)
{
ret =ret * i;
}
return ret;
}
6-3 求一个大于10的n位整数w的后n-1位的数,并作为函数值返回。
c复制代码
#include<math.h>
int fun(int w)
{
int sum = 0;
int count = 0;
int num = w;
while (num)
{
num /= 10;
count++;
}
sum = w % (int) (pow(10, count - 1));
return sum;
}
6-4 其右上三角(含主对角线)元素之和。
c复制代码
int fun(int a[3][3])
{
int sum1 = 0, sum2 = 0;
for (int i = 0; i < 3; i++)
{
for (int j = i; j < 3; j++)
{
sum1 += a[i][j];
}
}
return sum1;
}
6-5 字符串比较
c复制代码
int fun(char a[], char b[])
{
if (strcmp(a, b) < 0)
return -1;
else if (strcmp(a, b) > 0)
return 1;
else
return strcmp(a, b);
}
6-6 使用函数求素数和
c复制代码
int prime(int p)
{
int count = 0;
if(p==1)
return 0;
for (int i = 2; i <= p; i++)
{
if (p % i == 0)
count++;
}
if (count == 1)
return 1;
else
return 0;
}
int PrimeSum(int m, int n)
{
int sum = 0;
for (int i = (m<=n?m:n); i <= (n>=m?n:m); i++)
{
if (prime(i) == 1)
sum += i;
}
return sum;
}
6-7 使用函数输出水仙花数
c复制代码
#include<math.h>
int narcissistic(int number)
{
int count = 0;
int sum1 = 0;
int num = number;
while (number)
{
number /= 10;
count++;
}
int sum = 0;
number = num;
while (number)
{
sum1 = number % 10;
sum += (int)(pow(sum1, count));
number /= 10;
sum1 = 0;
}
if (num == sum)
return 1;
else
return 0;
}
void PrintN(int m, int n)
{
for (int i = (m <= n ? m : n)+1; i < (n >= m ? n : m); i++)
{
if (narcissistic(i) == 1)
{
printf("%d\n", i);
}
}
}
二.编程题
7-1 寻找自守数
c复制代码
#include<stdio.h>
int ZISHOUnum(int p)
{
int num = 0, count = 0;
num = p * p;
while (p != 0)
{
if (p % 10 != num % 10)
return 0;
p /= 10;
num /= 10;
}
return 1;
}
int main()
{
int n = 0, m = 0;
int count = 0;
scanf("%d %d", &n, &m);
for (int i = n; i <= m; i++)
{
if (ZISHOUnum(i))
{
count++;
printf("%d\n", i);
}
}
if (count == 0)
{
printf("None\n");
}
return 0;
}