例3-1 求 x 的 n 次方
#include<iostream>
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:"<<endl;
cin>>x>>y;
cout<<"x power y is "<<power(x,y)<<endl;
return 0;
}
例3-2 二进制转化为十进制
#include<iostream>
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 "<<val<<endl;
return 0;
}
例3-3 求 PI 的值
#include<iostream>
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 "<<PI<<endl;
return 0;
}
例3-4 寻找特殊的 m