将三个数按从大到小输出、两数值交换、找最大值,求最大公约数
1.将三个数按从大到小输出
使用冒泡法:
1)其中排序总轮数为:元素个数-1
2)每次的内部循环数为:元素个数-当前轮数-1
3)每次都是两两进行比较,将大的值放在前面,较小的放在后面
将数字从小到大输出也是一样的思路。
#include<stdio.h>
int main()
{
int a[3] = {0};
int i, j;
printf("请输入三个数:");
for (i = 0; i<3; i++)
{
scanf("%d", &a[i]);
}
//总共排序轮数 :元素个数-1
for (i = 0; i < 2; i++)
{
//内层循环次数:元素个数-当前轮数-1
for (j = 0; j<3-i-1; j++)
{
if (a[j]<a[j + 1])
{
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
printf("%d %d %d", a[0], a[1], a[2]);
system("pause");
return 0;
}
2、给定两个整形变量的值,将两个值的内容进行交换
定义中间变量
#include<stdio.h>
#include<stdlib.h>
//两个数进行交换
int main()
{
int a;
int b;
int temp;
scanf("%d %d", &a,&b);
temp = a;
a = b;
b = temp;
printf("a=%d b=%d\n",a,b);
system("pause");
return 0;
}
3.找出10个整数中的最大值
#include<stdio.h>
//求10 个整数中最大值。
int main(){
int i = 0;
int a[10] = {1,2,3,4,5,6,7,8,0,9};
for (i = 1; i <= 9; i++)
{
if (a[0] < a[i])
{
a[0] = a[i];
}
}
printf("%d是最大值",a[0]);
system("pause");
return 0;
}
4、求最大公约数
#include<stdio.h>
//最大公约数
//辗转相除法
int main()
{
int a, b, c;
while (1)
{
printf("输入两个数字求最大公约数:");
scanf("%d%d", &a, &b);
c = a%b;
while (c != 0)
{
a = b;
b = c;
c = a%b;
}
printf("最大公约数为:%d\n", b);
}
system("pause");
return 0;
}
函数:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
long gcd(long m, long n)//最大公约数
{
if (n == 0)
return m;
else
return gcd(n, m % n);
}
int main()
{
long n, m;
scanf("%ld%ld", &n, &m);
printf("%ld\n", gcd(n, m));
system("pause");
return 0;
}