练习(对两个整型变量的值进行交换、求10 个整数中最大值、将三个数按从大到小输出、求两个数的最大公约数)

1.给定两个整型变量的值,将两个值的内容进行交换

分析:

利用临时变量对两个整型变量进行交换

代码:

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

int main(){
	int a = 10;
	int b = 20;
	int c;
	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;
}

运行结果:

改进:(不允许创建临时变量,交换两个数的内容)

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

int main(){
	int a = 10;
	int b = 20;
	printf("a=%d,b=%d\n", a, b);
	a = a + b;  //和
	b = a - b;  //a
	a = a - b;  //b
	printf("交换后,a=%d,b=%d\n", a, b);
	system("pause");
	return 0;
}

2.求10 个整数中最大值

代码:

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

int main(){
	int i = 0,max=0;
	int arr[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
	printf("现有10个数字:0,1,2,3,4,5,6,7,8,9\n");
	for (i; i < 10; i++){
		max = arr[0];
		for (i; i<10; i++){
			if (arr[i] >max){
				max = arr[i];
			}
		}
	}
	printf("10个数中最大的为:%d\n", max);
	system("pause");
	return 0;
}

运行结果:

改进:

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

int main(){
	int i = 0, max = 0;
	int arr[10];
	printf("请输入10个数字\n");

	for (i; i < 10; i++){
		scanf("%d", &arr[i]);
		if (arr[i] >max){
		   max = arr[i];
		  }
	}
	printf("10个数中最大的为:%d\n", max);
	system("pause");
	return 0;
}

运行结果:

3.将三个数按从大到小输出

代码:

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

int main(){
	int i, j, m;
	int arr[3];
	printf("请输入3个数字\n");
	for (i = 0; i < 3; i++){
		scanf("%d", &arr[i]);
	}
		for (j = 0; j <3; j++){
			for (i=0; i <2-j; i++){
				if (arr[i] < arr[i + 1]){
					m = arr[i];
					arr[i] = arr[i + 1];
					arr[i + 1] = m;
				}
			}
		}
		printf("三个数由大到小排列:\n");
	for (i; i < 3; i++){
		printf("%d  ", arr[i]);
	}
	system("pause");
	return 0;
}

运行结果:

4.求两个数的最大公约数

分析:

先选出a,b中较小的那一个数字,再利用for循环对较小数逐个减一并寻找能整除a和b的整数。

代码:

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

int main(){
	int a, b, min;
	printf("请输入两个数字:\n");
	scanf("%d %d", &a,&b);
	if (a < b){
		min = a;
	}
	else{
        min = b;
	}
	
	for (min; min>0; min--){
		if (a%min == 0 && b%min == 0){
			printf("最大公约数为:%d\n", min);
			break;
		}
	}
	system("pause");
	return 0;
}

运行结果:

猜你喜欢

转载自blog.csdn.net/qq_42142477/article/details/82825643