1.水仙花数
打印出所有"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身.
例:153=1的三次方+5的三次方+3的三次方.
法1:
#include<stdio.h>
int main()
{int i = 0;int j = 0;int k = 0;for (i = 1; i < 10; i++)//百位{for (j = 0; j < 10; j++)//十位{for (k = 0; k < 10; k++)//个位{if (i * i * i + j * j * j + k * k * k == i * 100 + j * 10 + k){printf("%d ", i * 100 + j * 10 + k);}}}}return 0;
}
运行结果:
153 370 371 407
法2:
#include<stdio.h>
int main()
{int n = 0;for (n = 100; n < 999; n++)//直接所有数循环{int i = n / 100;//百位int j = n / 10 % 10;//十位int k = n % 10;//个位if (i * i * i + j * j * j + k * k * k == i * 100 + j * 10 + k){printf("%d ", i * 100 + j * 10 + k);}}return 0;
}
2.整型数组内函数求和
法1:
#include<stdio.h>
int main()
{int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };int sz = sizeof(arr) / sizeof(arr[0]);int i = 0;int ret = 0;for (i = 0; i < sz; i++){ret += arr[i];}printf("%d ", ret);return 0;
}
法2:采用函数方法
#include<stdio.h>
int sum(int arr[], int n)
{int ret1 = 0;int i = 0;for (i = 0; i < n; i++){ret1 += arr[i];}return ret1;
}
int main()
{int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };int sz = sizeof(arr) / sizeof(arr[0]);int ret = sum(arr, sz);printf("%d ", ret);return 0;
}
3.斐波那契数列
类似于1 1 2 3 5 8 13 21 34......
#include<stdio.h>
//1 1 2 3 5 13
int main()
{int arr[15] = { 0 };arr[0] = 1;arr[1] = 1;int i = 0;for (i = 2; i < 15; i++){arr[i] = arr[i - 1] + arr[i - 2];}for (i = 0; i < 15; i++){printf("%d ", arr[i]);}return 0;
}
运行结果:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
4.杨辉三角
杨辉三角的每行行首和每行行尾的数都为1.而且每个数等于其左上及其正上方两数只和.
法1:
#include<stdio.h>
int main()
{int arr[11][11] = { 0 };int i = 0;int j = 0;arr[0][0] = 1;for (i = 0; i < 11; i++){printf("\n");for (j = 1; j <= i; j++){arr[i][j] = arr[i - 1][j] + arr[i - 1][j - 1];printf("%3d", arr[i][j]);}}return 0;
}