習題筆記 錢能 第4章節

mrlixuec發表於2019-02-24

目錄

EX0401  //簡單 函式計算 pow() sqrt,定義都是double型的 

EX0402 // 無用 

EX0403  計算C1813,避免溢位 方法一如下 方法二如課本,人工去除無用部分

EX0404  浮點數的比較方法,對標頭檔案的註釋,精度寬度:cout.precision() or setprecision()

 

EX0405  **浮點數是不能用於位操作的 ,故先把浮點數空間對映成為整型實體

EX0406   (!(n%3)<<2)+(!(n%5)<<1)+(!(n%5)) 精髓在於: 將結果轉為二進位制編碼,並由對應數字和switch操作進行輸出。其次,運算子的優先順序。

EX0407   程式碼無意義,掌握這樣簡約的風格 

EX0408  二進位制轉換成十進位制        strlen()或者str.length() 操作


EX0401  //簡單 函式計算 pow() sqrt,定義都是double型的 

#include<iostream>
using namespace std;
#include<cmath>
int main()
{ int x;
cout<<"input x"<<endl;
cin>>x;
double result=sqrt(pow(sin(x),2.5));
cout<<result;
system("pause");
}

EX0402 // 無用 

#include<iostream>
#include<cmath>
using namespace std;

int main()
{
int e=1,f=4,g=2;
 double m=10.5;double n=4.0,k;
 k=(e+f)/g+sqrt(n)*1.2/g+m;
 cout<<k<<endl;
 system("pause");
}

EX0403  計算C1813,避免溢位 方法一如下 方法二如課本,人工去除無用部分

#include<iostream>
#include<cmath>
using namespace std;

long long int get_jiecheng(int x);

int main()
{
long long int t;
t=get_jiecheng(18)/(get_jiecheng(13)*get_jiecheng(5));
cout<<t<<endl;
long int a;
cout<<"long int:"<<sizeof(a)<<endl;
system("pause");

}
long long int get_jiecheng(int x)
{ long long int result=1;
for(int i=1;i<=x;i++)
    result*=i;
cout<<result<<endl;
return result;
}

EX0404  浮點數的比較方法,對標頭檔案的註釋,精度寬度:cout.precision() or setprecision()

#include<iostream>
#include<fstream>  //for file"abc.txt"
#include<sstream>
#include<cmath>   //for abs()
using namespace std;
#include<string>
void test(string str,long long int c);
int main()
{const long long int c=20922789888000;

ifstream fin("abc.txt");
string str;
while(getline(fin,str))
    test(str,c);
system("pause");
}
void test(string str,long long int c)
{
long double a,b,t;
istringstream sin (str);
sin>>a;sin>>b;
t=a*b;
cout.precision(9);
if(fabs(t-c)<1e-6) cout<<a<<"     "<<b<<endl;
}
 

 

EX0405  **浮點數是不能用於位操作的 ,故先把浮點數空間對映成為整型實體

#include<iostream>
using namespace std;

int main()

{

const long double x=12345.67891023456;
char *temp = (char *) &x;
int k=1;
for(int i=0;i<5;i++) for(;k<9;k++) cout<<(temp+i)>>k&1;


}

EX0406   (!(n%3)<<2)+(!(n%5)<<1)+(!(n%5)) 精髓在於: 將結果轉為二進位制編碼,並由對應數字和switch操作進行輸出。其次,運算子的優先順序。

#include<iostream>
using namespace std;
#include<fstream>
#include<sstream>
#include<string>


int main()
{string str;

    ifstream fin("abc.txt");
    int a;int  tag =0;
        while (getline(fin,str))
        {
            for(istringstream sin(str);sin>>a;)
            { if(a%3==0) tag+=1;if(a%5==0)  tag+=2;if(a%7==0) tag+=3;
            switch(tag){
                  case 1:  cout<<"3"<<endl;
                  case 2:   cout<<"5"<<endl;
                  case 3:   cout<<"7"<<endl;
            }}
        }
    system("pause");

}

EX0407   程式碼無意義,掌握這樣簡約的風格 

int a=1,b=2,c=3; 

int s,w=0,t=1;

s=(b<c &&c>0? a+b:0);

 

EX0408  二進位制轉換成十進位制        strlen()或者str.length() 操作

相關文章