c++的一些基礎程式碼
阿新 • • 發佈:2020-12-20
標題輸入一個八位二進位制 化為十進位制
if include < iostream>
using namespace std;
//計算x 的口次方
double power (double x , int n) ;
int main () {
int value=O;
cout<< "Enter an 8 bi t binary number: ";
for (int i=7; i>=O; i--) {
char ch;
cin>>ch;
if (ch== '1')
va1ue+=static_cast< int> (power (2 , i));//強制型別轉化
cout<<"Decimal va1ue is "<<va1ue<<end1;
return 0;
doub1e power (double x , int n) {
double val= 1 .0;
while (n--)
va1 *= Xi
return va1;
編寫程式求π 的值,公式如下。
π= 16arctan( 1/5)-4arctan(1/239)
arctanx 用泰勒展開
//3 3.cpp
# incl ude < iostream>
using namespace std;
double arctan (double x) {
double sqr=x*x;
double e=x;
double r=O;
int i=l;
while (e/i> 1e-15) {
double f=e/i;
r=(i%4==l)?r+f: r-f;
e=e*sqr;
i+ = 2;}
return r
}
int main () (
double a=16.0 *arctan(1/5.0);
doub1e b= 4.0 *arctan( 1/ 239.0);
//注意:因為整數相除結果取整,如果引數寫為1/5 , 1/239 ,結果就都是0。
cout<<"PI=" <<a-b<<end1;
return 0;
sinx近似值
(泰勒級數展開)
include < iostream>
inc1ude <crnath> //標頭檔案cmath 中具有對C++ 標準庫中數學函式的說明
using namespace std;
const double TINY VALUE= 1e-10;
double tsin (double x) {
double g= 0;
double t=x;
int n=l;
do {
g+=t;
n++ ;
t=-t *x *x/(2 *n-l)/(2 *n- 2) ;
} while (fabs (t) >=TINY VALUE);
return g;
}
int main () {
doub1e k , r , s;
cout<< "r=" ;
cin>>r;
cout<< "s=";
cin>> s;
if (r *r<=s *s)
k=sqrt(tsin(r) *tsin(r) +tsin(s) *tsin(s));
else
k=tsin (r *s) /2;
cout<< k<< end1;
return 0;