c++语言程序设计(郑莉)第四版第三章例子实现


例3-1 求 x 的 n 次方

#include
using namespace std;
double power(double x,int y)
{
	double val = 1;
	for( ;y>=1 ;y--)
	val*=x;
	return val;
}
int main()
{
	double x;
	int y;
	cout<<"please enter x and y:"<>x>>y;
	cout<<"x power y is "<

例3-2 二进制转化为十进制

#include
using namespace std;
int power(int x,int y)
{
	int val = 1;
	for( ;y>=1 ;y--)
	val*=x;
	return val;
}
int main()
{
	int val = 0;
	cout<<"Enter an 8 bit binary number:";
	for(int i = 7; i >= 0; i--)
	{
		char ch;
		cin>>ch;
		if(ch == '1')
		{
			val += power(2,i);
		}
	}
	cout<<"Decimal number is "<

例3-3 求 PI 的值

#include
using namespace std;
double arctan(double x)
{
	double sqr = x*x;
	double e = x;
	double r = 0;
	int i = 1;
	while(e/i > 1e-15)
	{
		double f = e/i;
		r = (i%4==1)?r+f:r-f;
		e = e*sqr;
		i+=2;
	}
	return r;
}
int main()
{
	double PI = 16 * arctan(1.0/5) - 4 * arctan(1.0/239);
	cout<<"PI is "<

例3-4 寻找特殊的 m

相关