计算机程序设计c++ 5-3:函数定义和调用例子

三个数中最大的值

比较三个数a, b, c, 找到其中最大的值;
方法:

  • 先比较第一个数与第二个数;
  • 再比较第一个数与第二个数中最大数与第三个数比较;
double maxThree(double a, double b, double c)
{
	double max;
	max = a > b? a : b;
	max = max > c? max: c;
	return max;
}

int main()
{
	double x1, x2, x3, max;
	char yes;
	do{
		cout << "input x1, x2, x3: ";
		cin >> x1 >> x2 >> x3;
		max = maxThree(x1, x2, x3);
		cout << "max vlaue: " << max << endl;
		cout << "continue (y/n)?"
		cin >> yes;
	} while(yes == 'Y' || yes='y')
}

二分查找法(折半查找)

  • 功能

    • 有序的数据序列中查找某个数据
  • 前提

    • 待查找数据序列已经排序
  • 假设:

    • 生序序列 a[a1, a2 , … , an]
  • 方法:

    • 比较大小:待查找数据与表的中位数am进行比较
      • 相等:x = am输出am序号
      • 小于:x < am, 在am之前的序列中二分查找x
      • 大于:x > am, 在am之后的序列中二分查找x

例子:
二分查找整数序列中的22
[9, 15, 18, 21, 23, 29, 32, 36, 39, 43, 46, 50, 54]

int binarySearch(int a[], int n, int key)
{
	int low=0, high=n-1, mid;
	while(low <= high)
	{
		mid = (low+high) / 2;
		if(key == a[mid])
		{
			return mid+1;
		}
		else if(key > a[mid])
		{
			low = mid + 1;
		}
		else if(key < a[mid)
		{
			high = mid - 1;
		}
	}
	return -1;
}

int main()
{
	int a[] = {9, 15, 18, 21, 23, 29, 32, 36, 39, 43, 46, 50, 54};
	int k, x;
	char again='n';
	do{
		cout << "target num? ";
		cin >> x;
		k = binarySearch(a, 18, x);
		if (k>= 0)
		{
			cout << x << " 是第" << k << "个数" << endl;
		}
		else
			cout << x << " 不在序列中!" << endl;
		cout << "是否还查找另外一个数(y获n)";
		cin >> again;
	} while(again=="yes" || again == 'y')
return 0;
}

秦九韶算法求多项式的值

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

函数功能:求多项式的值

double qinJS(double aa[], int nn, double xx)
{
	double y = 0;
	for(int i=nn-1; i>=0; i--)
	{
		cout << "第" << nn-i << "次循环" << aa[i] << "+" << xx << "*" << y << endl;
		y = aa[i] + xx *y;
	}
	return y;
}


int main()
{
	int n;
	double a[100], x, ydl;
	cout << "项数? "<< endl;
	cin >> n;
	for(int i=0; i<n; i++)
	{
		cout << "第" << i+1 << "项的系数?" << endl;
		cin >> a[i];
	}
	y = qinJS(a, n, x);
	cout << "当x=" << x << "时, f(x)=" << y << endl;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

uncle_ll

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值