Hello World
老规矩还是先见识一下输出“Hello World!”:
1 2 3 4 5 6 7 8
| #include <iostream>
using namespace std;
int main(){ cout << "Hello World!"; return 0; }
|
注意几点:
- #include 这一部分和c是一样的,但是后面的库的名字是不同的;
- using namespace std; 是为了不需要后面每次使用像 cout 时得写全成 std::cout 。而且记得一定要在后面加上 ;;
- cout 是c output,想输出什么东西都得按照 cout << 这样来。
其他的都跟c是一样的:int main(){}、return 0; 以及每行结尾的 ;。
输入/输出
如果输入为
则用 cin 来接收输入,然后输出想要的内容:
1 2 3 4 5 6 7 8 9 10 11
| #include <iostream>
using namespace std;
int main(){ int a,b,c; cin >> a >> b >> c; cout << a << " " << b << " " << c; return 0; }
|
基本数据类型
跟c语言一样,定义一个变量时需要给定数据类型:
名称 |
类型 |
范围 / 精度 |
整型 |
int |
-2,147,483,648 ~ 2,147,483,647 |
长整型 |
long long |
-9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807 |
单精度浮点型 |
float |
精度约 6~7 位 |
双精度浮点型 |
double |
精度约 15~16 位 |
字符 |
char |
ASCII 码范围:0 ~ 127 |
布尔值 |
bool |
true / false |
字符串 |
string |
任意长度,取决于内存 |
例子:
1 2 3
| long long a = 100000000000000LL; long long b = 1000000000LL * 1000000000LL; long long c = 1LL * 1000000000 * 1000000000;
|
1 2 3 4
| float a = 3.0f / 2;
float b = 3 / 2; cout << b << '\n';
|
1 2
| double a = 2.5; double b = 3.0 / 2;
|
1 2
| char ch = 'A'; cout << ch + 1 << '\n';
|
1 2 3
| bool found = false; found = true; if (found) cout << "Yes\n";
|
1 2 3 4 5
| string s = "hello"; cout << s[1] << '\n'; cout << s.size() << '\n'; string t = s + "world"; cout << t << '\n';
|
控制语句
这些内容跟c语言一模一样:
if:
1 2 3 4 5 6 7 8
| int score = 85; if (score >= 90) { cout << "优秀\n"; } else if (score >= 60) { cout << "及格\n"; } else { cout << "不及格\n"; }
|
for:
1 2 3 4
| for (int i = 1; i <= 5; i++) { cout << i << " "; }
|
while:
1 2 3 4 5
| int i = 1; while (i <= 5) { cout << i << " "; i++; }
|
do…while:
1 2 3 4 5
| int i = 1; do { cout << i << " "; i++; } while (i <= 5);
|
break:
1 2 3 4 5
| for (int i = 1; i <= 10; i++) { if (i == 5) break; cout << i << " "; }
|
continue:
1 2 3 4 5
| for (int i = 1; i <= 5; i++) { if (i == 3) continue; cout << i << " "; }
|