PS:全文代码均为本人手写,如有错误,欢迎各位私信指正错误,如有疑问,欢迎私信询问。觉得文章有用的小伙伴多多点赞+收藏+关注,各位的支持是作者之后更新文章的最大动力!希望我的分享能给大家带来帮助!
- 输入年份和月份判断天数(包含闰年的判断)
cpp
#include<stdio.h>
int judgeleapyear(int y)
{
int lp = 0;
if (y%4==0 && y%100!=0 || y%400==0)
{
lp = 1;
}else
{
lp = 0;
}
return lp;
}
int judgedays(int y, int m)
{
int days = 0;
if (m==4 || m==6 || m==9 || m==11)
{
days = 30;
}else if (m==1 || m==3 || m==5 || m==7 || m==8 || m==10 || m==12)
{
days = 31;
}else if (judgeleapyear(y) == 1)
{
days = 29;
}else
{
days = 28;
}
return days;
}
int main(void)
{
int y = 0;
int m = 0;
printf("Input year and month:\n");
scanf("%d%d",&y,&m);
printf("%d\n",judgedays(y,m));
return 0;
}
- 打印100以内的素数
cpp
#include<stdio.h>
int judgeprime(int a)
{
int i = 0;
int j = 1;
for (i = 2; i < a-1; ++i)
{
if (a%i == 0) //不是素数的条件
{
j = 0;
break;
}
}
return j;
}
void printfprime(int n)
{
int i = 0;
for (i = 2; i <= n; ++i)
{
if (judgeprime(i) == 1)
{
printf("%d\n",i);
}
}
}
int main(void)
{
int n = 100;
printfprime(n);
return 0;
}
- 比较三个数的最大值
cpp
#include<stdio.h>
int numMax3(int a, int b, int c)
{
int max = 0;
if (b > a)
{
max = b;
}else if (b == a)
{
max = b;
}else
{
max = a;
}
if (c > max)
{
max = c;
}else if (c == max)
{
max = c;
}
return max;
}
int main(void)
{
int a = 0;
int b = 0;
int c = 0;
printf("Input three num:\n");
scanf("%d%d%d",&a,&b,&c);
printf("max = %d\n",numMax3(a,b,c));
return 0;
}
- 递归实现 n!(n的阶乘)
cpp
#include <stdio.h>
int fact (int n)
{
if (n == 1)
{
return 1;
}else
{
return fact (n-1) * n;
}
}
int main(void)
{
int n = 0;
printf("Input a num:\n");
scanf("%d",&n);
printf("%d\n",fact(n));
return 0;
}
- 递归实现斐波那契数列前n项和计算
cpp
#include <stdio.h>
int fibo (int n)
{
if (n==1 || n==2 )
{
return 1;
}else
{
return fibo (n-1) + fibo (n-2) ;
}
}
int fibosum (int n)
{
if (n==1 || n==2)
{
return n;
}else
{
return fibosum (n-1) + fibo(n);
}
}
int main(void)
{
int n = 0;
printf("Input a num:\n");
scanf("%d",&n);
printf("fibo(%d) = %d\n",n,fibo(n));
printf("sum = %d\n",fibosum(n));
return 0;
}
- 数组逆序
cpp
#include<stdio.h> //数组逆序
void arrayRever (int a[], int len)
{
int t = 0;
int i = 0;
for (i = 0; i < len/2; ++i)
{
t = a[i];
a[i] = a[len-1-i];
a[len-1-i] = t;
}
}
void printArray(int a[],int len)// 数组输出
{
int i = 0;
for (i = 0; i < len; ++i)
{
printf("a[%d] = %d\n", i, a[i]);
}
}
int main(void)
{
int a[6] = {9,8,7,6,5,4};
int len = 6; //计算给出数组长度为len
arrayRever(a,len);
printArray(a,len);
return 0;
}