黑马程序员匠心之作|C++教程从0到1入门编程
关于P16~P18练习
1、基本知识:加减乘除,取模,递增递减
#include <iostream>
using namespace std;
int main() {
//1、前置递增
int a = 10;
++a;//让变量+1
cout <<"a=" <<a << endl;
//2、后置递增
int b = 10;
b++;//让变量+1
cout << "b=" << b << endl;
//3、前置与后置区别
//前置递增,先让变量+1,然后进行表达式运算
int a2 = 10;
int b2 = ++a2 * 10;
cout << "a2=" << a2 << endl; //11
cout << "b2="<<b2 <<endl; //110,先+1后×10
//后置递增,先进行表达式运算,然后让变量+1
int a3 = 10;
int b3 = a3++ * 10;
cout << "a3=" << a3 << endl; //11
cout << "b3=" << b3 << endl; //100,先a3×10,后a3+1
//加减乘除
int a1 = 10;
int b1 = 3;
cout << a1 + b1 << endl;
cout << a1 - b1 << endl;
cout << a1 * b1 << endl;
cout << a1 / b1 << endl; //两个整数相除,结果为整数,小数部分去除,3
cout << a1% b1 << endl; //取模运算本质就是求余数,1
int a2 = 10;
int b2 = 20;
cout << a2 / b2 << endl; //0
cout << a2 % b2 << endl; //结果为10,
int a3 = 10;
int b3 = 0;
//cout << a3 / b3 << endl; //非法操作,两数相除,除数不为零
//cout << a3 % b3 << endl; //非法操作,两数相除,除数不为零,所以做不了取模运算
//两个小数相除,不可以取模运算
double d1 = 0.5;
double d2 = 0.22;
cout << d1 / d2 << endl;//运算结果可以是小数
system("pause");
return 0;
}
关于P19~P20练习
1、基本知识:
赋值运算符:=,+=,-=,*=,/=,%=;
比较运算符:==,!=,>,<,>=,<=;
//赋值运算
// =
int a = 10;
a = 100;
cout << "a=" << a << endl;
// +=
a = 10;
a += 2; //a=a+2
cout << "a=" << a << endl; //12
// -=
a = 10;
a -= 2; //a=a+2
cout << "a=" << a << endl; //8
// *=
a = 10;
a *= 2;
cout << "a=" << a << endl; //20
// /=
a = 10;
a /= 2;
cout << "a=" << a << endl; //5
// %=
a = 10;
a %= 2;
cout << "a=" << a << endl; //0
//比较运算符
// ==
int a = 10;
int b = 20;
cout << (a == b) << endl; //0
// !=
cout << (a != b) << endl; //1
// >
cout << (a > b) << endl; //0
// <
cout << (a < b) << endl; //1
// >=
cout << (a >= b) << endl; //0
// <=
cout << (a <= b) << endl; //1
关于P21~P23练习
1、基本知识:
逻辑运算符:非!,与&&,或||
//逻辑运算符
//非!
int a = 10;
//在C++中,除了0,皆为真
cout << !a << endl; //真变假,假变真,0
cout << !!a << endl; //1
//与&&,同真为真,其余为假
a = 10;
int b = 10;
cout << (a && b) << endl;//1
a = 0;
b = 10;
cout << (a && b) << endl;//0
a = 0;
b = 0;
cout << (a && b) << endl;//0
//或||,同假为假,其余为真
a = 10;
b = 10;
cout << (a || b) << endl;//1
a = 0;
b = 10;
cout << (a || b) << endl;//1
a = 10;
b = 0;
cout << (a || b) << endl;//1
a = 0;
b = 0;
cout << (a || b) << endl;//0