C++程序的基本格式;输入、输出;数据类型;算术运算符;自增/自减运算符;复合运算符;关系运算符;逻辑运算符;分支语句(if-else)
C++程序的基本格式:
#include<iostream>
using namespace std;
int main(){
/*程序语句*/
return 0;
}
include
包含
iostream
标准库,用于输入输出流。包含了istream
和ostream
,i=input,o=output
using namespace std
是对命名空间的声明,std=standard
流式输入、输出:cin
输入,cout
输出
cout << "Hello World!\n"; //转义字符:\n 换行 \t tab制表位
cout << "Hello World!" << endl;
cout << "Hello World!" << "Hello World!"<< endl; //输出两个语句
cout << "Hello World!Hello World!"<< endl;
cout << "Hello World!\nHello World!"<< endl;
cout << "Hello World!" <<endl<< "Hello World!"<< endl;
cin
与cout
类似,但是使用<<
,注意与>>
运算符朝向相反。
cin >> 项目1 >> 项目2 >> ... >> 项目n;
数据类型:(最好掌握每种数据类型的取值范围)
int
整型
float
单精度浮点型
double
双精度浮点型
bool
布尔型(只有真/假两种值)
char
字符型
string
字符串型
cout << 34 << endl; //整型数字 int
cout << 3.14159 << endl; //浮点型数字 float double
cout << 'A' << endl; //字符 char <care>
cout << "This is a C++ program." << endl; //字符串 string
cout << true << endl; //布尔型 bool
cout << false << endl;
算术运算符:加+
,减-
,乘*
,除/
,模运算(取余)%
#include <iostream> //头文件、函数、变量都需要先声明后使用
#include <cmath> //也可以写作math.h,pow()和sqrt()都需要
using namespace std;
int main() {
cout << 36 + 5 << endl; //加法
cout << 36 - 5 << endl; //减法
cout << 36 * 5 << endl; //乘法
cout << 36 / 5 << endl; //除法***
cout << 36 % 5 << endl; //求余,模运算mod
cout << pow(5, 2) << endl; //乘方power,pow(x,y)=x的y次方
cout << pow(3,3) << endl; //27
cout << pow(2,10) << endl; //1024
cout << sqrt(36) << endl; //开平方,开根号
return 0;
}
C++中的除法运算:
在C++中,a/b的除法运算有两种情况,
1. 如果a和b均为整数,则a/b的结果为整数;
2. 如果a或b中有浮点数(包括均为浮点数),则a/b的结果为浮点数。
注意,在第1种情况,结果的整数不是四舍五入,而是直接去除小数点及其后面的部分。
另外,在a/b中,b不能为0,否则将抛出错误。
cout << 3 / 5 << endl;
cout << 3.0 / 5 << endl;
cout << 3 / 5.0 << endl;
cout << 3.0 / 5.0 << endl;
自增运算符++
,自减运算符--
复合运算符:+= -= *= /= %=
int a = 10, b = 20, c = 30, d = 40, e = 50;
a += 30;
cout << "a=" << a << endl;
b -= 10;
cout << "b=" << b << endl;
c *= 5;
cout << "c=" << c << endl;
d /= 10;
cout << "d=" << d << endl;
e %= 8;
cout << "e=" << e << endl;
选择结构:
单分支if
语句
if(条件)
满足条件时执行;
双分支if-else
语句
if(条件)
满足条件时执行;
else
不满足条件时执行;
关系运算符:>
大于,>=
大于等于,<
小于,<=
小于等于,==
等于,!=
不等于
逻辑运算符:与&&
,或||
,非!
理解下列表达式的值,体会各种运算符的优先级
cout << (5 && 6) << endl;
cout << (1 && -1) << endl;
cout << (1 < 2 && 5) << endl;
cout << (3 - 3 && 5) << endl;
cout << (3 - 3 || 5) << endl;
cout << (0 || 5 - 5) << endl;
cout << (!0) << endl;
cout << (!(2 > 1)) << endl;
- 参加人数
- 43
- 创建人