C/PTA —— 10.函数1(课外实践)

  • 一.函数题
    • 6-1 符号函数
    • 6-2 求排列数
    • 6-3 求一个大于10的n位整数w的后n-1位的数,并作为函数值返回。
    • 6-4 其右上三角(含主对角线)元素之和。
    • 6-5 字符串比较
    • 6-6 使用函数求素数和
    • 6-7 使用函数输出水仙花数
  • 二.编程题
    • 7-1 寻找自守数

一.函数题

6-1 符号函数

int sign(int x){if (x > 0)return 1;else if (x == 0)return 0;elsereturn -1;}

6-2 求排列数

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位的数,并作为函数值返回。

#includeint 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 其右上三角(含主对角线)元素之和。

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 字符串比较

int fun(char a[], char b[]){if (strcmp(a, b) < 0)return -1;else if (strcmp(a, b) > 0)return 1;elsereturn strcmp(a, b);}

6-6 使用函数求素数和

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;elsereturn 0;}int PrimeSum(int m, int n){int sum = 0;for (int i = (m<=n" />:n); i <= (n>=m?n:m); i++){if (prime(i) == 1)sum += i;}return sum;}

6-7 使用函数输出水仙花数

#includeint 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;elsereturn 0;}void PrintN(int m, int n){for (int i = (m <= n " />: n)+1; i < (n >= m ? n : m); i++){if (narcissistic(i) == 1){printf("%d\n", i);}}} 

二.编程题

7-1 寻找自守数

#includeint 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;}