【C++學習教程01】C++名稱空間重名&函式原型&字元型別&資料型別
阿新 • • 發佈:2021-01-02
目錄
參考資料
- 均來自範磊C++教程(1-4課時)
- 開發平臺Xcode
程式碼
學習內容十分的簡單,因此直接用程式碼體現。
#include <iostream> #include <iomanip> #include <locale> namespace a{ int b=5; } namespace c { int b=8; } using namespace std; using namespace c; using namespace a; //******** //函式又叫做【方法】,PLC程式設計中通常叫做【Method】 int show(int a, int b){ cout<<"函式呼叫"<<endl; return a+b; } //********* //規範的操作時先宣告函式【函式原型】,在再最後面進行定義,這樣可以防止重複呼叫 void A(); void B(); void swap(int,int); void A(){ cout<<"function A is used"<<endl; B(); } void B(){ cout<<"function B is used"<<endl; } void swap(int x, int y){ int z; cout<<"before change"<<x<<","<<y<<endl; z=x; x=y; y=z; cout<<"after change"<<x<<","<<y<<endl; } //********* //在任意函式之外的變數宣告成為全域性變數 int golbal_a=3; int global_b=4; int main(int argc, const char * argv[]) { int b=9; cout << b<<"\n"<<endl; //"\n"和"endl"作用一樣 cout << c::b<<endl; /*重名問題*/ cout << a::b<<endl; //******** char char_s='A'; int int_s; int_s=char_s; cout << int_s <<endl; //******** A(); //******** swap(golbal_a,global_b); cout<<"after change"<<golbal_a<<","<<global_b<<endl; //******** unsigned char char_test; char_test=65; //整型自動轉化為字元型 cout<<"char is "<<char_test<<endl; cout<<"char is "<<(int)char_test<<endl; //********此段程式碼無效? //setlocale(LC_ALL,"chs"); //wchar_t w[]=L"中"; //wcout<<w; float f_a=1123456789;//雖然也是4個位元組但是他的指數位有8位//對有效數字的理解 cout<<f_a<<endl; cout<<setprecision(15)<<f_a<<endl;//有效數字位數為6~7位 double f_b=1.234567891987654321;//8位元組 指數位11位 cout<<setprecision(15)<<f_b<<endl;//有效數字位數為15~16位 //const double PI=3.1415926; //PI=3.14;//此時會發生報錯 enum num{zero, one=100, two, three, four}; cout<<zero<<endl;//不指定的話就會自動設定為0 cout<<one<<endl; cout<<two<<endl;//指定後自動加1 enum day{sun,mon , tus, wed, thur,fir,sat};//增加程式可讀性 day today; today=tus; cout<<tus<<endl; //******** int temp_a; double temp_b; cout << "input 2 int num"<<endl; cin>>temp_a;//中間用空格表示區分 //輸入字元變數等時無效顯示為0 cin>>temp_b;//輸入double時候,會退1法。 int a=show(temp_a,temp_b);//數值採用退1法//但是不準確 cout << temp_a <<endl; cout << temp_b <<endl; cout << a <<endl; return 0; }
輸出結果:
資料型別
參考見: 菜鳥論壇.