C语言练手小代码---two

1. 给定两个整形变量的值,将两个值的内容进行交换。
#define _CRT_SECURE_NO_WARNINGS ch
#include<stdio.h>
#include<Windows.h>

int main(){
	int a = 10;
	int b = 20;
	int temp = 0;
	temp = a;
	a = b;
	b = temp;
	printf("a=%d ", a);
	printf("b=%d ", b);
	system("pause");
	return 0;
}

运行结果:

2. 不允许创建临时变量,交换两个数的内容【两种方法来实现】
#define _CRT_SECURE_NO_WARNINGS ch
#include<stdio.h>
#include<Windows.h>

int main(){
	int a = 10;
	int b = 20;
	a = a + b;//如果a和b为int的最大值,则可能产生溢出,所以下边介绍一种采用位运算的方法来实现
	b = a - b;
	a = a - b;
	printf("a=%d ", a);
	printf("b=%d ", b);
	system("pause");
	return 0;
}
#define _CRT_SECURE_NO_WARNINGS ch
#include<stdio.h>
#include<Windows.h>

int main(){
	int a = 10;
	int b = 20;
	a = a^b;
	b = a^b;
	a = a^b;
	printf("a=%d ", a);
	printf("b=%d ", b);
	system("pause");
	return 0;
}

运行结果:

3.求10 个整数中最大值。

#define _CRT_SECURE_NO_WARNINGS ch
#include<stdio.h>
#include<Windows.h>

int main(){
	int arr[10] = { 0, 1, 2, 4, 5, 6, 7, 3, 9, 8 };
	int max = arr[1];
	int i = 0;
	int sz = sizeof(arr)/sizeof(arr[0]);
	for (i = 0; i < sz; i++){
		if (arr[i]>max){
			max = arr[i];
		}
	}
	printf("%d\n", max);
	system("pause");
	return 0;
}

运行结果:

4.将三个数按从大到小输出。(此处采用了冒泡排序)

#define _CRT_SECURE_NO_WARNINGS ch
#include<stdio.h>
#include<Windows.h>

int main(){
	int arr[3] = { 0, 1, 2};
	int i = 0;
	int j = 0;
	int temp = 0;
	int sz = sizeof(arr)/sizeof(arr[0]);
	for (i = 0; i < sz-1; i++){
		for (j = 0; j < sz - i; j++){
			if (arr[j] < arr[j + 1]){
				temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
	for (i = 0; i < sz; i++){
		printf("%d ",arr[i]);
	}
	system("pause");
	return 0;
}

运行结果:

5.求两个数的最大公约数。(注:最小公倍数=(m*n)/最大公约数)

#define _CRT_SECURE_NO_WARNINGS ch
#include<stdio.h>
#include<Windows.h>
//辗转相除法
int main(){
	int m = 24;
	int n = 18;
	while (m%n){
		int temp = m;
		m = n;
		n = temp%n;
	}
	printf("%d ", n);
	system("pause");
	return 0;
}

结果:

猜你喜欢

转载自blog.csdn.net/superwangxinrui/article/details/79949939