C语言实验专栏 (代码可免登录复制)
⭐ 倒推
#include
int main(){
int i = 1,n;
scanf("%d",&n);
while(n-- >1)
{
i += 1;
i *= 2;
}
printf("Totals=%d",i);
return 0;
}
⭐ 暴力枚举 (a * a + b * b == c * c)
#include
#include
int main(){
int n,a,b,c;
int cnt = 0;
bool flag = false;
scanf("%d", &n);
for (c = n; c < 1000; c++)
{
flag = false;
for (a = 1; a < c; a++)
{
for (b = c - 1; b > 0; b--)
{
if (a*a + b*b == c*c)
{
cnt++;
printf("NO%d:%d\n",cnt, c);
if (cnt == 4)
return 0;
flag = true;
break;
}
}
if (flag)
break;
}
}
return 0;
}
⭐ 小优化版
#include
int main(){
int n,a,b,c;
int cnt = 0;
//bool flag = false;
int flag = 0;//用 int 代替 布尔,防止忘记导入文件
scanf("%d", &n);
for (c = n; c < 1000; c++)
{
flag = 0;
// a 从 根号 c 开始枚举
for (a = sqrt(c); a < c; a++)
{
for (b = c - 1; b > sqrt(c); b--)
{
if (a*a + b*b == c*c)
{
cnt++;
printf("NO%d:%d\n",cnt, c);
if (cnt == 4)
return 0;
flag = 1;
break;
}
}
if (flag)
break;
}
}
return 0;
}
⭐ 暴力枚举
#include
int main(){
int i,st,end,res = 0;
scanf("[%d,%d]",&st,&end);
for(i = st; i <= end; i++)
{
if((i % 4 == 0 && i % 100 != 0) || i % 400 == 0)
res++;
}
printf("years=%d",res);
return 0;
}
⭐ 辗转相除法(欧几里得定理)求最大公约数
⭐ 最小公倍数 = a * b / 最大公约数
#include
int gcd(int a,int b){
return b ? gcd(b,a%b) : a;
}
int main(){
int n,m,i,j;
scanf("%d,%d",&n,&m);
int gys = gcd(n,m);
int gbs = n*m/gys;
printf("gys=%d,gbs=%d",gys,gbs);
return 0;
}
⭐ 浮点数绝对值:fabs( )
#include
#include
double fact(int n){
if(n == 1)
return 1;
return (double)n * fact(n-1);
}
int main ()
{
double x;
int i;
scanf("%lf",&x);
double s = x;
double t = 1.0;
for(i = 2; fabs(t) >= 0.000001;i++){
t = pow(x,i)/fact(i);
s += t;
}
printf("s=%.2f",s);
return 0;
}
⭐ 斐波那契
#include
int main(){
int i,n;
scanf("%d",&n);
double sum = 0.0,son = 2.0,mon = 1.0;
for(i = 0; i < n; i++){
sum += son/mon;
son = son+mon;
mon = son-mon;//友情提示:这里的 son的值是(son+mon)
}
printf("s=%.2lf",sum);
return 0;
}
⭐ 自定义函数判断参数 x 是否为完备数
#include
int check(int x){
int sum = 0,j;
for(j = 1; j < x;j++){
if(x % j == 0)
sum += j;
}
if(sum == x)
return 1;
return 0;
}
int main(){
int i,n;
scanf("%d",&n);
for(i = 6; i <= n; i++){
if(check(i)){
printf("%d\n",i);
}
}
return 0;
}
⭐ i 枚举的是月份
#include
int main()
{
int year,month,day,days,i,d;
scanf("%d %d %d",&year,&month,&day);
days=0;
for(i=1;i<month;i++)
{
switch(i)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
d = 31;
break;
case 4:
case 6:
case 9:
case 11:
d = 30;
break;
case 2:
if((year%4==0 && year%100!=0) || year%400==0)
d=29;
else
d=28;
default:
break;
}
days += d;
}
printf("%d\n",days+day);
return 0;
}