1.写两个函数,分别求两个整数的最大公约数和最小公倍数,用主函数调用两个函数,并输出结果,两个整数由键盘输入。
#include <iostream>
using namespace std;
int main() {
int lcd(int, int);
int hcf(int, int, int);
int m, n;
cin >> m >> n;
int p, q;
p = lcd(m, n);
cout << "lcd=" << p << endl;
q = hcf(m, n, p);
cout << "hcf=" << q << endl;
}
int lcd(int x,int y) {//最小公倍数
int num,temp;
if (x < y) {//排序
temp = x;
x = y;
y = temp;
}
while ((x % y) != 0) {
num = y;
y = x % y;
x = num;
}
return y;
}
int hcf(int x,int y,int z) {//最大公约数
int hcf = x * y / z;
return hcf;
}
运行结果:
3.写一个判断素数的函数,在主函数中输入一个整数,输出是否为素数的信息
#include <iostream>
using namespace std;
int main() {
int PrimeNum(int);
int a;
cout << "请输入一个整数:";
cin >> a;
PrimeNum(a);
return 0;
}
int PrimeNum(int x) {
bool flag = true;
if(x == 2){
cout << "2是一个素数" << endl;
}
for (int i = 2; i < x; i++) {
if (x % i == 0) {
flag = false;
break;
}
}
if(flag){
cout<< x <<"是一个素数"<<endl;
}
else{
cout<< x <<"不是一个素数"<<endl;
}
}
运行结果:
9.Hanoi 汉诺塔问题
这是一个经典的数学问题:古代有一个梵塔,塔内有3个座 A , B , C .开始时 A 座上有64个盘子,盘子大小不等,大的在下,小的在上(见图4.16)。有一个老和尚想把这64个盘子从 A 座移到 C 座.但每次只允许动一个盘。且在移动过程中在3个座上都始终保持大盘在下,小盘在上。在移动过程中可以利用 B 座,要求编程序打印出移动的步骤。
#include <iostream>
using namespace std;
int main() {
void hanoi(int n, char one, char two, char three);
int m;
cout << "input the number of disks:";
cin >> m;
cout << "The steps of moving" << m << "disks:" << endl;
hanoi(m, 'A', 'B', 'C');
return 0;
}
void hanoi(int n, char one, char two, char three)//将n个盘从one座借助two座移动到three盘
{
void move(char x, char y);
if (n == 1) {//如果只剩一个盘,直接从A移动到C
move(one, three);
}
else {
hanoi(n - 1, one, three, two);//借助C将A上的n-1个盘从A移动到B
move(one, three);//将A剩下的一个盘移动到C
hanoi(n - 1, two, one, three);//再借助A把B上的n-1个盘从B移动到C
}
}
void move(char x, char y) {
cout << x << "-->" << y << endl;
}
运行结果:
10.用递归法将一个整数n转换成字符串。例如,输入483,应输出字符串“483”。n的位数不确定,可以是任意位数的整数。
#include <iostream>
using namespace std;
int main() {
int n;
void convert(int);
cout << "请输入一个整数:";
cin >> n;
if (n < 0) {
cout << "-";
n = -n;
}
convert(n);
}
void convert(int n) {
int i;
char c;
if ((i = n / 10) != 0) {
convert(i);
}
c = n % 10 + '0';
cout << " " << c;
}
注:'0'对应的ASCII码是65或者某一个数,9就是一个数字9,要将9装换成字符'9',就需要'0'+9,因为'9'-'0' = 9
12.三角形的面积为:area = sqrt(s*(s-a)*(s-b)*(s-b))
其中,s=1/2 *(a+b+c),a,b,c为三角形的三边。定义两个带参数的宏,一个用来求s,另一个用来求area。编写程序,在程序中用到实参的宏名来求面积area
#include <iostream>
#include <cmath>
using namespace std;
#define S(a,b,c) (a+b+c)/2
#define AREA(a,b,c) sqrt(S(a,b,c)*(S(a,b,c)-a)*(S(a,b,c)-b)*(S(a,b,c)-c))
int main() {
float a, b, c;
cout << "请输入a,b,c:";
cin >> a >> b >> c;
if (a + b > c && b + c > a && a + c > b) {
cout << "area=" << AREA(a, b, c) << endl;
}
else {
cout << "非三角形!" << endl;
}
return 0;
}
运行结果: