3种方法交换两个整数(不创建临时变量)+输出一组数据最大值+简单排序+最大公约数

交换两个整数:
第一种:

	int a = 6;
	int b = 8;
	int t = 0;
	t = a;
	a = b;
	b = t;
	printf("a = %d b = %d\n", a, b);

后两种不创建临时变量
第二种:

	int a = 6;
	int b = 8;
	a = a + b;
	b = a - b;//b = 6
	a = a - b;//a = 8;
	printf("a = %d b = %d\n", a, b);

第三种:

	int a = 6;
	int b = 8;
	a = a ^ b;
	b = a ^ b;//b = 6
	a = a ^ b;//a = 8
	printf("a = %d b = %d\n", a, b);

输入一组数据,并输出这组数据的最大值:

#include<stdio.h>
/*
	输入一组数据,输出最大值
*/
int max(int a[]) {

	//int k = 0;
	//for (int i = 0;i<9;i++){
	//	if (a[k]<a[i+1]) {
	//		k = i + 1;
	//	}
	//}
	//return a[k];
	int max = 0;
	for (int i = 0; i < 10;i++) {
		if (max < a[i]) {
			max = a[i];
		}
	}
	return max;

}
int main() {

	int a[10];
	printf("Please input 10 numbers in the screen:\n");
	for (int i = 0; i < sizeof(a)/4; i++) {
		scanf("%d", &a[i]);
	}
	printf("The max number of these datas is %d\n", max(a));
	return 0;

}

输入3个数,按从大到小的顺序输出:

#include<stdio.h>
/*
	输入3个数,按从大到小的顺序输出
*/
int main() {

	int a = 0, b = 0, c = 0;
	int t = 0;
	printf("Please input 3 numbers (every number is separated with space) :\n");
	scanf("%d %d %d", &a, &b, &c);	
	if (a < b) {
		t = a;
		a = b;
		b = t;
	} 
	if (a < c) {
		t = a;
		a = c;
		c = t;
	}
	if (b < c) {
		t = b;
		b = c;
		c = t;
	}
	printf("The 3 numbers from big to small: %d %d %d\n", a, b, c);
	return 0;

}

输入两个数,求这两个数的最大公约数:

#include<stdio.h>
/*
	求两个数的最大公约数
*/
int main() {

	int a = 0, b = 0;
	int judge = 0;
	printf("Please input 2 numbers:");
	scanf("%d %d", &a, &b);
	while ((judge = a % b) != 0) {
		a = b;
		b = judge;
	}
	printf("The max common divisor is : %d\n", b);
	return 0;

}

猜你喜欢

转载自blog.csdn.net/qq_42957923/article/details/83449791