27、写一个函数,交换两个整形变量的值
//写一个函数,交换两个整形变量的值
#include<iostream>
#include<stdlib.h>
using namespace std;
//交换结果只存在于子函数中,主函数中x,y值不变
int swap1(int x, int y)
{
int t;
t = x;
x = y;
y = t;
cout << x << "," << y << endl;
return 0;
}
int swap2(int &x, int &y)
{
int t;
t = x;
x = y;
y = t;
cout << x << "," << y << endl;
return 0;
}
int swap3(int *x, int *y)
{
int t;
t = *x;
*x = *y;
*y = t;
cout << *x << "," << *y << endl;
return 0;
}
int main()
{
int x, y;
//int a=1, b=2;
int *p = &x, *q = &y;
cin >> x >> y;
//cout << swap(x,y) << endl;
swap1(x,y);
cout << x << "," << y << endl;
swap2(x,y);
cout << x << "," << y << endl;
swap3(p,q);
cout << *p << "," << *q << endl;
system("pause");
return 0;
}
28、求两个数的最大公约数,欧几里得算法(辗转相除法)
//求两个数的最大公约数,欧几里得算法(辗转相除法)
#include<iostream>
#include<stdlib.h>
using namespace std;
int getGCD(int x, int y)
{
int t,a=1;
if(x<y)
{
t = y;
y = x;
x = t;
}
while(a!=0)
{
a = x%y;
//if(t==0) break;
x = y;
y = a;
}
return x;//多执行一次x=y;y=a;所以返回x,不返回y
}
int main()
{
int a,b;
cin >> a >>b;
cout << getGCD(a,b) << endl;
system("pause");
return 0;
}
29、求两个数的最小公倍数
//求两个数的最小公倍数
#include<iostream>
#include<stdlib.h>
using namespace std;
int getGCD(int x, int y)
{
int t,a=1;
if(x<y)
{
t = y;
y = x;
x = t;
}
while(a!=0)
{
a = x%y;
//if(t==0) break;
x = y;
y = a;
}
return x;//多执行一次x=y;y=a;所以返回x,不返回y
}
int getLCM(int x , int y)
{
return x*y/getGCD(x,y);
}
int main()
{
int a,b;
cin >> a >>b;
cout << getLCM(a,b) << endl;
system("pause");
return 0;
}
总结
1、交换两个整形变量的三个函数中,swap1()使用两个整数做形参,交换结果只在函数内部起作用,应使用指针或引用做形参;参考:C++中两个变量交换的三种方法,以及对指针的理解
2、求最大公约数(Greatest Common Divisor)基本思想:两数相除,以除数和余数反复做除法运算,当余数为 0 时,取当前算式除数为最大公约数
3、求最小公倍数(Least Common Multiple)基本思想:a*b == 最大公约数 x 最小公倍数