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 最小公倍數