我們要include的東西就不一樣了
原本C是 include <stdio.h> 和 <stdlib.h>
而C++則是 include <iostream>和<cstlib>
再來是重要的命名空間使用 using namespace std;
來說說有using和沒有using的差別好了
有using namespace std ,就直接可以使用cout和endl
例如: cout<<"hello world!<<endl;
沒有使用using namespace std,就不能直接使用cout和endl
例如: std::cout<<"hello world!<<std::endl;
差別就是每次要使用時,都必須要再寫一次 std::
下面這個範例是在說明:
1. 布林值boolean: 在C++宣告時候,寫 bool ok; ,回傳true即是1,反之false則是0。
2. 利用cin和cout與使用者作互動 cout<<"Width:"; cin>>"width"; 注意小於大於的方向哦。
#include <iostream>
#include <cstdlib>
//std:使用命名空間,像是java的import
using namespace std;
int main(){
//cout: 印出 ,<<: 分隔、導向的作用,endl: 換行
//cout的c: console主控台
cout<<"Hello World!!"<<endl;
//bool: boolean資料型態
bool ok;
ok = (7>3);
if(ok){
cout<<"correct!"<<endl;
} else{
cout<<"not correct"<<endl;
}
cout<<"--------------------"<<endl;
int width, heigh, area;
cout<<"width:"; cin>>width;
cout<<"heigh:"; cin>>heigh;
area = width*heigh;
cout<<"width:"<<width<<",heigh:"<<heigh<<",Area:"<<area<<endl;
return 0;
}
執行結果:

沒有留言:
張貼留言