#include <iostream> //头文件
using namespace std; //标准命名空间
int main() //主函数
{
cout << "Hello World" << endl;
return 0;
}
| 部分 | 作用 |
|---|---|
#include <iostream> | 包含输入输出工具包 |
using namespace std; | 使用标准命名空间 |
int main() | 主函数,程序入口 |
{ } | 函数体 |
cout | 输出到屏幕 |
endl | 换行 |
return 0; | 程序正常结束 |
书写规范:每行语句以英文分号 ; 结尾;区分大小写;必须用英文符号。
例题1:输出自我介绍
#include <iostream>
using namespace std;
int main()
{
cout << "My name is Tom." << endl;
return 0;
}
输出:My name is Tom.
| 功能 | 语法 | 要点 |
|---|---|---|
| 输出 | cout << "内容"; | << 输出箭头,字符串加双引号 |
| 换行 | cout << "内容" << endl; | endl 表示 end of line |
| 输入 | cin >> 变量名; | >> 输入箭头,与 cout 方向相反 |
| 多输入 | cin >> x >> y; | 多个变量连续输入 |
例题2:输入两个整数,输出它们的和
#include <iostream>
using namespace std;
int main()
{
int x, y;
cin >> x >> y;
cout << x + y << endl;
return 0;
}
输入:3 5
输出:8
易错:cin 用 >>,cout 用 <<;不要漏分号。
| 类型 | 含义 | 示例 |
|---|---|---|
int | 整数型 | int age = 10; |
float | 浮点型 | float price = 2.5; |
string | 字符串 | string name = "小明"; |
定义与赋值:
int score; // 定义
score = 100; // 赋值
int score = 100; // 定义并赋值
命名规则:只能含字母、数字、下划线;不能数字开头;不能用关键字;区分大小写;见名知义。
正确:number1、Apple_2、NumOfApples
错误:1number、else、5 8
例题3:计算长方形周长和面积
#include <iostream>
using namespace std;
int main()
{
int width = 500, height = 880;
int C = (width + height) * 2;
int S = width * height;
cout << "周长:" << C << "米" << endl;
cout << "面积:" << S << "平方米" << endl;
return 0;
}
输出:周长:2760米;
面积:440000平方米
| 运算符 | 含义 | 示例 |
|---|---|---|
+ | 加法 | a + b |
- | 减法 | a - b |
* | 乘法 | a * b |
/ | 除法 | a / b,整数除法只保留商 |
% | 取模 | a % b,求余数 |
示例:15 / 2 = 7,15 % 2 = 1。
表达式:由操作数和运算符组成,如 (width + height) * 2。
例题4:输入两个整数,输出和、差、积、商
#include <iostream>
using namespace std;
int main()
{
int x, y;
cin >> x >> y;
cout << "x+y=" << x + y << endl;
cout << "x-y=" << x - y << endl;
cout << "x*y=" << x * y << endl;
cout << "x/y=" << x / y << endl;
return 0;
}
输入:30 15
输出:x+y=45;x-y=15;x*y=450;x/y=2
例题5:跑步时间换算
#include <iostream>
using namespace std;
int main()
{
int h, m, s;
cin >> s;
h = s / 3600;
s = s - h * 3600;
m = s / 60;
s = s - m * 60;
cout << h << " " << m << " " << s << endl;
return 0;
}
输入:1235
输出:0 20 35
// 注释内容/* 注释内容 */#include <iostream> 或 using namespace std;main 没有 int 返回值类型,缺少 return 0;cin 写成 <<,cout 写成 >>练习1:输出菱形(对角线5个星)
#include <iostream>
using namespace std;
int main()
{
cout << " * " << endl;
cout << " *** " << endl;
cout << "*****" << endl;
cout << " *** " << endl;
cout << " * " << endl;
return 0;
}
练习2:景区门票计算(成人120元,小孩半价,老人6折)
#include <iostream>
using namespace std;
int main()
{
int x, y, z, s;
cin >> x >> y >> z;
s = 120 * x + 60 * y + 72 * z;
cout << s << endl;
return 0;
}
输入:5 4 10
输出:1560
#include <bits/stdc++.h> //万能头文件 using namespace std; int main(){
return 0; }
整数:int longlong 浮点数:float double 字符串:char 布尔类型:bloom
保留小数有效位: cout<<fixed<<setprecision(2); cout<<3.14159;
格式化输入输出: %d整数,%f浮点数 ,%.2浮点数(2位小数),%c字符,%s字符串
求圆的面积 double r, s; scanf("%lf",&r) printf("圆的半径=%d,面积=%.2f",r,s)