C语言初学

1、辗转相除法的实现

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
int main()
{
	int a = 0;
	int b = 0;
	int r = 0;
	int temp = 0;
	scanf("%d %d", &a, &b);
	if (a < b)
	{
		temp = a;
		a = b;
		b = temp;
	}
	printf("%d", a);
	r = a % b;
	while(1)
	{
		if (r == 0)
		{
			printf("最大公约数是:%d\n",b);
			break;
		}
		temp = r;
		r = b % temp;
		b = temp;
	}
	return 0;

优化

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
int main()
{
	int a = 0;
	int b = 0;
	int r = 0;
	scanf("%d %d", &a, &b);
	while (a % b)
	{
		r = a % b;
		a = b;
		b = r;
	}
	printf("最大公约数是:%d\n", b);
	return 0;
}

反思:1、辗转相除法求最大公约数的大小比较是不必的。

2、循环条件的优化。

3、变量的减少使用可以提高程序运行的速度与效率,也能提高cpu运行效率。

 2、goto用法和自动关机程序等

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
int main()
{
	system("shutdown -s -t 120");
	char input[] = { 0 };
again:
	printf("Your computer will shutdown in 60s,please enter the correct code.\n");
	scanf("%s", input);
	if (strcmp(input, "iamapig") == 0)
		//密码中如果含有空格就不行
	{
		system("shutdown -a");
	}
	else
	{
		goto again;
		//C语言中goto可以指向几乎任何位置
	}
	return 0;
}

3、输出1~100中的素数

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
int main()
{
	int i = 0;
	int j = 0;
	for (i = 1; i <= 100; i+=2)//偶数不可能是素数
	{
		for (j = 2; j < sqrt(i); j++)
		{
			if (i % j == 0)
			{
				break;
			}
		}
		if (i % j != 0)
		{
			printf("%d ", i);
		}
	}
	return 0;
}

4、输出1000到2000中的闰年

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
int main()
{
	int y = 0;
	int count = 0;
	for (y = 1000; y <= 2000; y++)
	{
		if ((y % 4 == 0) && (y % 100 !=0 ) || (y % 400 == 0))
		{
			printf("%d ", y);
			count++;
		}
	}
	printf("\n%d", count);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值