计算机程序设计C++(第7周基础练习)

计算机程序设计C++ MOOC

测试与作业C++基础练习100题

##第七周基本练习

本周为指针的使用,指针是C++中非常重要的一个工具

  1. 两个数的排序
    在这里插入图片描述
#include "iostream"

using namespace std;

void sort(int *a, int *b)
{
	int temp;
	if (*a > *b)
	{
		temp = *a;
		*a = *b;
		*b = temp;
	}
}


int main()
{
	int a, b;
	cin >> a >> b;
	sort(&a, &b);
	cout << a << " " << b << endl;
	return 0;
}
  1. 三个数的排序
    在这里插入图片描述
#include "iostream"

using namespace std;

void sort(int *a, int *b)
{
	int temp;
	if (*a > *b)
	{
		temp = *a;
		*a = *b;
		*b = temp;
	}
}

void sort(int *a, int *b, int *c)
{
	sort(a, b);
	sort(b, c);
	sort(a, b);
}


int main()
{
	int a, b,c;
	cin >> a >> b >> c;
	sort(&a, &b, &c);
	cout << a << " " << b <<" " << c << endl;
	return 0;
}
  1. 返回数组的统计值(最大、最小、平均值、标准差)
    在这里插入图片描述
#include "iostream"
#include "cmath"

using namespace std;

void statistics(double a[], int n, double *max, double *min, double *avg, double *stdev)
{
	int i = 0;
	*max = a[0];
	*min = a[0];
	*avg = a[0];
	*stdev = 0;
	for (i = 1; i < n; i++)
	{
		*max = a[i] > *max ? a[i] : *max;
		*min = a[i] < *min ? a[i] : *min;
		*avg += a[i];
	}
	*avg /= n;
	for (i = 0; i < n; i++)
	{
		*stdev  += (a[i] - *avg)*(a[i] - *avg);
	}
	*stdev = sqrt(*stdev / n);
}

int input(double a[])
{
	int i = 0, n;
	while (1)
	{
		cin >> n;
		if (n != -9999)
		{
			a[i] = n;
			i++;
		}
		else
		{
			break;
		}
	}
	return i;
}

int main()
{
	double a[100], max, min, avg, stdev;
	int n;
	n = input(a);
	statistics(a, n, &max, &min, &avg, &stdev);
	cout << max << " " << min << " " << avg << " " << stdev << endl;
	return 0;
}
  1. 通过指向函数的指针调用函数
    在这里插入图片描述
#include "iostream"
#include "cmath"

using namespace std;

double x2(double x)
{
	return x*x;
}

double mysin(double x)
{
	return 2 * sin(2 * 3.14 * 2 * x + 3.14);
}

int main()
{
	double(*f)(double);
	double x;
	cin >> x;
	f = x2;
	cout << f(x) << " ";
	f = mysin;
	cout << f(x) << endl;
	return 0;
}
  1. 计算任意一元函数值的通用函数
    在这里插入图片描述
#include "iostream"
#include "cmath"

using namespace std;

double x2(double x)
{
	return x*x;
}

double mysin(double x)
{
	return 2 * sin(2 * 3.14 * 2 * x + 3.14);
}

double anyfun(double(*f)(double), double x)
{
	return (*f)(x);
}

int main()
{
	double x;
	cin >> x;
	cout << anyfun(x2, x) << " ";
	cout << anyfun(mysin, x) << endl;
	return 0;
}
  1. 计算函数在指定区间的近似平均值
    在这里插入图片描述
#include "iostream"
#include "cmath"

using namespace std;

double myexp(double x)
{
	return exp(x);
}

double mysin(double x)
{
	return sin(x);
}

double mycos(double x)
{
	return cos(x);
}

double funavg(double(*f)(double), double a, double b, int n)
{
	double avg = 0,h=(b-a)/n;
	for (int i = 0; i <= n; i++)
	{
		avg += (*f)(a + i*h);
	}
	return avg / (n + 1);

}
int main()
{
	double a,b;
	cin >> a >> b;
	cout << funavg(myexp, a, b, 1000) << " ";
	cout << funavg(mysin, a, b, 1000) << " ";
	cout << funavg(mycos, a, b, 1000) << endl;
	return 0;
}

以上为第七周的基础练习。

猜你喜欢

转载自blog.csdn.net/qq_35779286/article/details/84036910