我与C语言之第二战!

  我与C语言第二战之第一题,给定两个整形变量的值,将两个值的内容进行交换。首先创建整形变量a=1,b=2,再创建中间变量c,令c=a,a=b,b=c即可,程序代码及交换前与交换后的运行结果如下:

#include <stdio.h>
#include <stdlib.h>
int main()
{
	int a = 1;
	int b = 2;
	int c = 0;
	printf("a=%d b=%d\n", a, b);
	c = a;
	a = b;
	b = c;
	printf("a=%d b=%d\n",a,b);
	system("pause");
	return 0;
}

  我与C语言第二战之第二题,不允许创建临时变量,交换两个数的内容。解法一,首先创建整形变量a=2,b=4,令a=a+b,b=a-b,a=a-b即可,程序代码及交换前与交换后的运行结果如下:

#include <stdio.h>
#include <stdlib.h>
int main()
{
	int a = 2;
	int b = 4;
	printf("a=%d b=%d\n", a, b);
	a = a + b;
	b = a - b;
	a = a - b;
	printf("a=%d b=%d\n", a, b);
	system("pause");
	return 0;
}

  我与C语言第二战之第二题,不允许创建临时变量,交换两个数的内容。解法二,首先创建整形变量a=3,b=5,用异或(^)运算,令a=a^b,b=a^b,a=a^b即可,程序代码及交换前与交换后的运行结果如下:

#include <stdio.h>
#include <stdlib.h>
int main()
{
	int a = 3;
	int b = 5;
	printf("a=%d b=%d\n", a, b);
	a = a^b;
	b = a^b;
	a = a^b;
	printf("a=%d b=%d\n", a, b);
	system("pause");
	return 0;
}

  我与C语言第二战之第三题,求10 个整数中最大值。首先定义一个存放十个整数的数组,int a【10】,用for循环控制输入的数的个数,然后利用scanf语句进行输入,因为数组的下标是从0开始的,所以取输入第一个数的地址a[0]为最大数,用a[i]存放其它九个数,i的范围为【1-9】,用for循环控制后面地址的个数,并用if语句进行判断,如果a[0]大,那么输出的便是a[0],反之输出的就是a[i],a[i]中的九个数在第二个for循环中进行比较,直到比出最大数。程序代码及运行结果如下:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

int main()
{
	int i = 0;
	int max = 0;
	int a[10] = {0};
	printf("请您输入10个数:\n");
	for (i = 0; i < 10; i++)
	{
		scanf("%d", &a[i]);
         max = a[0];
	}
	
	for (i = 1; i < 10; i++)
	{
		if (a[i]>max)
		{
			max = a[i];
		}
	}
	printf("您输入的10个数最大的数为:%d\n", max);
	system("pause");
	return 0;
}

  我与C语言第二战之第四题,将三个数按从大到小输出。首先定义一个存放三个整数的数组,int a[3],定义变量i,用以在for循环中控制循环次数,利用scanf语句进行三个数值的输入,用刚才定义的数组进行接收,用for语句进行循环,比较变量大小,定义一个中间变量t,用冒泡法实现数值交换,如果前一个数比后一个数小,交换两个数的数值,最后再用for语句、printf语句进行排序结果之后的输出。具体代码及程序运行结果如下:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main()
{
	int i,j,t= 0;
	int a[3] = { 0 };
	printf("请您输入三个数:\n");
	for (i = 0; i < 3; i++)
	{
		scanf("%d", &a[i]); 
	}
	for (i = 0; i < 2; i++)         
	{
		for (j = i + 1; j < 3; j++)  
		{
			if (a[i] < a[j])        
			{
				t = a[i];
				a[i] = a[j];
				a[j] = t;
			}
		}
	}
	for (i = 0; i < 3; i++)
	{
		printf("%d ", a[i]);  
	}
	printf("\n");
	system("pause");
	return 0;
}

  我与C语言第二战之第五题,求两个数的最大公约数。利用辗转相除法,取两个数中最大的数做除数,较小的数做被除数,用最大的数除较小数,如果余数为0,则较小数为这两个数的最大公约数,如果余数不为0,用较小数除上一步计算出的余数,直到余数为0,则这两个数的最大公约数为上一步的余数。首先利用scanf语句进行两个数值的输入,用if语句判断这两个数的大小,如果前一个数小于后一个数,利用中间变量进行两个数值的转换,如果大于,则直接执行下一个判断语句。程序代码及运行结果如下所示:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main()
{
	int a, b, t = 0;
	printf("请输入两个数:\n");
	scanf("%d%d", &a, &b);
	if (a < b)
    {
		t = a;
		a = b;
		b = t;
	}
	while (a%b != 0)
    {
		t = a%b;
		a = b;
		b = t;
	}
	printf("最大公约数为:%d\n", b);
	system("pause");
	return 0;
}

  这次和C的战斗让我有点受伤,冒泡排序也是查了相关资料才掌握, 还是自己的编程能力不足,需要尽快加强!Go!

猜你喜欢

转载自blog.csdn.net/weixin_43761659/article/details/84447104