C++学习笔记 第三章 函数

1.斐波那契数列

 

#include<stdio.h>
int Fib(int x) {
	if (x <3) {
		printf("return 1!\n");
		return(1);
	}
	else {
		printf("Fib(%d) and Fib(%d)\n", x - 2, x - 1);
		return(Fib(x - 2) + Fib(x - 1));
	}

}
int main() {

	int n, y;
	printf("Please enter a number:");
	scanf("%d", &n);
	y = Fib(n);
	printf("%d is the Fib number\n", y);
	return 0;
}

形参传递不改变main函数中实参的值,用&x定义一个引用,同时对其进行初始化,使其指向一个已存在的对象,从而对其操作相当于对实参进行操作,改变实参的值。(swap函数)

 

2.函数重载

 

#include<stdio.h>
#include<cmath>

double max1(double x, double y) {
	if (abs(x - y) <1e-10)      //判断浮点数是否相等的常见处理方式
		return x;
	else if (x >= y)
		return x;
	else return y;
}
int max1(int x, int y) {
	if (x == y)
		return x;
	else if (x > y)
		return x;
	else return y;
}
int max1(int x, int y, int z) {
	return max1(max1(x, y), z);
}
double max1(double x, double y, double z) {
	return max1(max1(x, y), z);
}
int main() {
	int a, b, c;
	double m, n, l;
	printf("Enter int a:");
	scanf("%d", &a);
	printf("Enter int b:");
	scanf("%d", &b);
	printf("Enter int c:");
	scanf("%d", &c);
	printf("max of %d and %d is %d\n", a, b, max1(a, b));
	printf("max of %d , %d and %d is %d\n", a, b, c, max1(a, b, c));
	printf("Enter double m:");
	scanf("%lf", &m);
	printf("Enter double n:");
	scanf("%lf", &n);
	printf("Enter double l:");
	scanf("%lf", &l);
	printf("max of %lf and %lf is %lf\n", m, n, max1(m, n));
	printf("max of %lf , %lf and %lf is %lf\n", m, n, l, max1(m, n, l));
	return 0;
}

double类型数据输入为%lf,输出可以是%f或%lf。

 

3.回文数

 

#include<stdio.h>
bool symm(unsigned n) {
	unsigned i = n;
	unsigned m = 0;
	while (i > 0) {
		m = m * 10 + i % 10;
		i /= 10;
	}
	return m == n;
}
int main() {
	for (unsigned m = 11; m < 1000; m++) {
		if (symm(m) && symm(m*m) && symm(m*m*m)) {
			printf("%d\n", m);
			printf("%d\n", m*m);
			printf("%d\n", m*m*m);

		}
		return 0;
	}
}

4.汉诺塔

#include <iostream>
using namespace std;
int k = 0;
//把src针的最上面一个盘子移动到dest针上
void move(char src, char dest) {
	cout << src << " --> " << dest << endl;
}

//把n个盘子从src针移动到dest针,以medium针作为中介
void hanoi(int n, char src, char medium, char dest) {
	if (n == 1) {
		move(src, dest);
		k++;
	}
	else {
		hanoi(n - 1, src, dest, medium);
		move(src, dest);
		k++;
		hanoi(n - 1, medium, src, dest);
	}
}

int main() {
	int m;
	cout << "Enter the number of diskes: ";
	cin >> m;
	cout << "the steps to moving " << m << " diskes:" << endl;
	hanoi(m, 'A', 'B', 'C');
	cout << k << endl;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值