c++学习笔记
清华mooc笔记补
之前的听课笔记-3.16
ch1-4
ch1
#include //编译预处理命令 包含cout cin等输入输出流的头文件 给出了语句声明
using namespace std;//iostream的名字空间在一个标准的名字空间中,防止后续重名
字符串/0 表示结束
const 符号常量 ,定义时给定初始值,const float pi=3.14159
int r;
cout << "input radius \n"<< endl;
cin >> r;
cout << "the radius is:" << r <<'\n'<< endl;
//常量与浮点数:
float r;
float c;
const float pi=3.1415;
cin >> r ;
c = 2 * pi * r;
cout << c << '\n';
//条件运算符与条件表达式:
int a;
int b, c;
cout <<" input a "<< '\n';
cin >> a;
cout << " input b" << '\n';
cin >> b;
c = a >= b ? (a * 3) : (b * 3);
cout << c << '\n';
//移位:
int b;
int a = 51;
b=sizeof(a);
cout << b;
a = a<<1;
cout << a;
a = a << 1;
cout << a;
a = a << 1;
cout << a;
//sizeof:
cout << "sg "<<'\t'<<'\t'<< sizeof(float) << "bytes."<<'\n';
char
字符char用单引号‘c’,字符串char用双引号“”
字符串定义:
C++中的字符串一般有以下四种类型,string/char/const char*/char[]
char x[] = “C++” ;//sizeof得4 字符串char可以直接printf(x);
string x = “c++”;//sizeof得28 string类型无法printf
int nLen = x.length();//C++长度length=3 ,该方法计算结果为字符串的实际长度,但是不是length(x)
bool a =0 || sizeof(int);
int nLen = x.length();
cout << x.length() <<sizeof(int)<<a<<endl;
// printf(x);
//符号位:
int s;
s = -50;
unsigned int a;
a = -50;//unsigned是无符号,仅仅可以表现0 or 正数,a实际存储并非-50
cout << a;
//if语句:
/*
int a, b;
cout << "input a and b" << endl;
cin >> a >> b;
if(a != b)
{
if (a > b)cout << "a>b" << '\n';
else cout << "a<b" << '\n';
}
else cout << "a=b" << '\n';
*/
//switch():注意break
switch (day)
{
case 1:cout << "monday" << endl; break;
case 2:cout << "tuesday" << endl; break;
case 3:cout << "wendesday" << endl; break;
case 4:cout << "thursday" << endl; break;
default:cout << "you are fault" << endl;
break;
}
枚举类型 enum
不能cin>>enum
#include <iostream>
using namespace std;
enum gameresult { WIN=0 ,LOSE=1, TIE =2,CANCEL= 3};//写在main之前
int main()
{
gameresult result;
//gameresult omit=CANCEL;
//gameresult omit = CANCEL;
for (int count = 0; count <= 3; count++)
{
result = gameresult(count);
if (result == CANCEL)
cout << "the game is cancel" << endl;
else if (result == WIN)cout << "the game we win" << endl;
else if (result==LOSE)cout<< "the game we lose" << endl;
else cout<< "the game we tie" << endl;
/* char m=static_cast<char> (result);
cout << "in the game we " << m << endl;//没有直接打印变量名的方法 ,只会打印出对应的0123
*/
}
return 0;
}
#include //编译预处理命令 包含cout cin等输入输出流的头文件 给出了语句声明
using namespace std;
enum result { win=1, lose=2, tie=3, cancel=4};
int main()
{
result x = win;
int a;
cin >> a;
if (a == win)
cout << "we win";
else {
if (a == cancel)
cout << "cancel the game";
else {
if (a == lose)
cout << "we lose";
else {
if (a == tie)
cout << "tie";
else
cout << "you are fault";
}
}
}
return 0;
}
//累加
int main()
{
int a = 0;
int sum = 0;
for (a = 0; a <= 9; a++)
sum = sum + a;
cout << sum;
return 0;
}
//分类计算面积:或者switch选择
#include <iostream>
using namespace std;
enum shapename { yuan=1, zhengfang,changfang };
int main()
{
shapename shape;
float a, b,r;
float s;
int count;
cout << "please input the shape:1yuan,2zhengfang,3changfang" << '\n' << endl;
cin >> count;
shape = shapename(count);
if(count==1)
{
cout << "the radius is:" << '\n';
cin >> r;
s = r * 3.14159 * r;
cout << s;
}
else if (count==2)
{
cout << "the length is:" << '\n';
cin >> r;
s = r * r;
cout << s;
}
else {
cout << "the length and width is:" << '\n';
cin >> a >> b;
s = a * b;
cout << s;
}
}
//struct结构体:
#include <iostream>
using namespace std;
struct wholetime {
unsigned int year;
unsigned int month;
unsigned int day;
unsigned int hour;
unsigned int min;
unsigned int sec;//int main之外定义struct
};
int main()
{
wholetime xx = { 2015,12,21,12,12,12 };
cout << "please input your year:";
cin >> xx.year;
cout << "please input your month:";
cin >> xx.month;
cout << "please input your day:";
cin >> xx.day;
cout << "please input your hour:";
cin >> xx.day;
cout << "please input your min:";
cin >> xx.min;
cout << "please input your sec:";
cin >> xx.sec;
cout << "the time is :"<<xx.year<<'\t'<<xx.month <<'\t'<<xx.day<<'\t'<<xx.hour<<'\t'<<xx.min<<'\t'<<xx.sec<<endl;
}
//二进制转十进制:
float power(float x, int N);
int main() {
char x;
int N=0;
int f = 0;
cout << "please input 8bit number:" << endl;
for (int i = 7; i >=0; i--) {
cin >> x;
if (x == '1')
N = N + power(2, i);
else if (x == '0')
N = N;
else {
cout << "fault";
f = 1;
break;
}
}
if(f!=1)
cout << N;
return 0;
}
/*
#include <iostream>
using namespace std;
double power(double x, int n);
//二进制转十进制
int main()
{
int inn;
int val=0;
//int sum=0;
cout << "please input 8 bytes numbers:";
for (int i = 8; i >= 1; i--) {
char inn;
cin >> inn;
if (inn=='1')//注意单引号
val +=static_cast<int>( power(2, (i-1)));
//sum = sum + val;
}
cout << val;
return 0;
}
*/
double power(double x, int n)
{
double val=1.0;
while(n--)
val = val * x;
return val;
}
//自写arctan程序,计算pi:
#include <iostream>
using namespace std;
double power(double x, int n);
double arctan(double x);
int main()
{
double pi;
double a = 16.0 * arctan(1 / 5.0);
double b = 4.0 * arctan(1 / 239.0);
pi = a- b;//int 整数相除结果取整,所以要写.0,否则1/5=0
cout << pi << endl;
}
double arctan(double x)
{
double val = 0;
double tmp=1;
int n=1;
int i = 0;
for (int n = 1; tmp > 1e-15; n = n + 2) {
val = power(-1, i) * power(x, n)/n + val;
i++;
tmp = power(x, n);
}
return val;
/*
double sqr = x * x;
double e = x;
double r = 0;
int i = 1;
while (e / i > 1e-15) {
double f = e / i;
r = (i % 4 == 1) ? r + f : r - f;
e = e * sqr;
i += 2;
}
return r;
*/
}
double power(double x, int n)
{
double val = 1.0;
while (n--)
val = val * x;
return val;
}
//单阶+平方+立方回文数:
#include <iostream>
using namespace std;
double power(double x, int n);
double valreturn(int x);
int main()
{
for (int x = 11; x <= 9999; x++) {
int tmp = 1;
double val=0;
double reval=0;
for (int n = 1; n <= 3; n++) {
val = power(static_cast<double>(x), n);
reval= valreturn(val);
if (val != reval)
tmp = 0;
}
if (tmp == 1) {
cout << x << '\t';
}
}
//cout << endl;
return 0;
}
double valreturn(int x) {
int m;
int tmp = 0;
do {
m = x % 10;
tmp = m + tmp*10;
x = x / 10;
} while (x);
return tmp;
}
double power(double x, int n)
{
double val = 1.0;
while (n--)
val = val * x;
return val;
}
//3-5分段函数,自写sin:sin(5)也能用麦克劳林展开吗?死活算不对
#include <iostream>
using namespace std;
double power(double x, int n);
int jiecheng(int n);
double tsin(double x);
int main()
{
double k;
double r, s;
cout << "r=:";
cin >> r;
cout << "s=:";
cin >> s;
if(r*r<=s*s){
k = sqrt(tsin(r) * tsin(r) + tsin(s) * tsin(s));
}
else {
k = 0.5 * tsin(r * s);
}
cout << "k=:"<<k;
//double xx = tsin(1.0);
//cout << xx;
/*double m, t;
cout << sin(5)<<endl;
t = tsin(5);
cout << t;*/
return 0;
}
double tsin(double x) {
double tmp = 1,tmpp=1;
int i = 0;
double m=0;
double a, b, c;
int n = 1;
//for (int n = 1; tmp >= 1e-10; n = n + 2)
/*
do{
//a = power(-1, i);
b = jiecheng(n);
tmp = power(x, n)/b;
n = n + 2;
b = jiecheng(n);
tmpp = power(x, n) / b;
m = m +tmp-tmpp;
n = n + 2;
//i++;
} while (tmp >= 1e-10);//就是不对,没找到bug
*/
double g = 0;
double t = x;
do {
g += t;
n++;
t = -t * x * x / (2 * n - 1) / (2 * n - 2);
} while (fabs(t) >= 1e-10);//浮点数绝对值fabs
return g;
}
int jiecheng(int n) {
int tmp = 1;
int m;
for (int m = 1; m <= n; m++) {
tmp = m * tmp;
}
return tmp;
}
double power(double x, int n)
{
double val = 1.0;
while (n--)
val = val * x;
return val;
}
//2021.01.31可用
float power(float x, int N);
double Factorial(int x);
double sinx(double x){
double y=0;
double tmp=1;
for (int i = 0; fabs(tmp) >= 1e-8; i++) {
tmp = power(x, (2 * i + 1)) * power(-1, i) / Factorial(2 * i + 1);
y += tmp;
}
return y;
}
double Factorial(int x) {
double y=1;
for (int i = 1; i <= x; i++)
y *= i;
return y;
}
//3-6扔骰子游戏:
#include <iostream>;
using namespace std;
#include <cstdlib>;//声明数值与字符串转化函数,伪随机数生成函数,动态内存分配函数等公共函数=c中的stdlib
int rolldice();
enum gamestatus { win, lose, playing };
int main()
{
int sum;
int mypoint;
gamestatus status;
unsigned seed;
int rolldice();
cout << "please input a seed number:";
cin >> seed;
srand(seed);//播种随机数种子;
sum = rolldice();//第一轮扔色子,计算和数;
switch (sum) {
case 7:
case 11: {status = win; break; }
case 2:
case 3:
case 12:{status = lose; break;
}
default:status = playing;
mypoint = sum;
cout << "the point is :" << mypoint << endl;
break;
}
while (status == win){
cout << "WIN!";
break;
}
while (status == lose) {
cout << "LOSE!";
break;
}
while (status == playing) {
sum = rolldice();
if (sum == 7) {
status = lose;
cout << "LOSE as 7";
}
if (status == mypoint) {
status = win;
cout << "WIN as equal";
}
}
}
int rolldice() {
int a = 1 + rand() % 6;
int b = 1 + rand() % 6;
int sum = a + b;
cout << "play roll is" << a << "+" << b<<"="<<sum<<endl;
return sum;
}
//反向输出:
do
{
tmp = x % 10;
y = tmp + y*10;
x = x / 10;
} while (x!=0);
cout << " " << y << endl;
//3-8递归:求阶乘
double Factorial(int x) {
double y;
if (x == 1)
y = 1;
else
y = Factorial(x - 1)*x;
return y;
}
//3-9组合:
int Combination(int m, int n) {
if (m < n)
return 0;
else {
if (m == n || n == 0)
return 1;
else
return Combination(m - 1, n) + Combination(m - 1, n - 1);
}
}
嵌套问题
3-10汉诺塔问题:自我嵌套 很重要 深思
int main() {
int hanuo(char a, char b, char c, int N);
//char a;
//char b;
//char c;
int N = 3;
hanuo('a', 'b',' c', N);
return 0;
}
int hanuo(char a,char b,char c,int N) {
if (N == 1)
cout << a << "->" << c << endl;
else {
hanuo(a, c, b, N - 1);
cout << a << "->" << c<<endl;
hanuo(b, a, c, N - 1);
}
return 0;
}
交换swap
void swap(int& x, int& y) {
int t = x;
x = y;
y = t;
}
int main() {
int x=1, y=2;
swap(x, y);
cout << x << " " << y << endl;
return 0;
}
含有可变参数的函数:
内联函数inline
const double pi = 3.14159266;
inline double cirarea(double r) {
return r * r * pi;
}
int main() {
double r;
cin>>r;
cout << cirarea(r) << endl;
return 0;
}
3-17重载函数
int main() {
double sumofsq(double x, double y);
int sumofsq(int x, int y);
int x, y;
double a, b;
cout << "please input int number" << endl;
cin >> x;
cout << "please input int number" << endl;
cin >> y;
cout << sumofsq(x,y) << endl;
cout << "please input double number" << endl;
cin >> a;
cout << "please input double number" << endl;
cin >> b;
cout << sumofsq(a,b) << endl;
return 0;
}
double sumofsq(double x, double y) {
return x * x + y * y;
}
int sumofsq(int x, int y) {
return x * x + y * y;
}
嵌套斐波那契数列
int fib(int x) {
if (x == 1 || x == 2)
return 1;
else
return fib(x - 1) + fib(x - 2);
}
判断浮点数是否相等,需要用减法后fabs<1e-10这种思路
类
class Clock{//好像类名大写首字母才不报错?
public://外部接口 可访问
void settime(int hour,int min,int sec);
void showtime();
private://内部私有 仅允许本类中函数访问
int hour = 0, minute = 0, second = 0;
protect://保护成员
}
Cock myclock;//定义类名 对象名;
类外访问:对象名.成员名 myclock.settime;
类的成员函数:可以在类外给出函数体实现,并在函数名前使用类名加以限定;
内联成员函数:提高效率,inline。
class Clock {
public:
void setTime(int hourh = 0, int min = 0, int sec = 0);
void showTime();
private:
int hour, minute, second;
};
void Clock::setTime(int hourh, int min, int sec) {
hour = hourh;
minute = min;
second = sec;
}
void Clock::showTime() {
cout << hour << ":" << minute << ":" << second << ":" << endl;
}
int main() {
Clock myclock;
myclock.setTime(14, 37, 25);
myclock.showTime();
return 0;
}
构造函数放在public
public:
Clock()=default;//指示编译器提供默认构造函数
Clock(int hourh,int min,int sec);//构造函数函数名与类名是一模一样的,没有返回值
例4-1/4-2
Clock::Clock(int hourh, int min, int sec) ://定义构造函数
hour(hourh), minute(min), second(sec) {//单冒号后 为初始化列表方式 形参赋值比赋值表达式效率更高
//无语句
}
Clock::Clock() : hour(0), minute(0), second(0) {}//默认构造函数
//无语句
int main() {
Clock myclock(0,0,0);//调用定义构造
myclock.showTime();
myclock.setTime(14, 37, 25);
myclock.showTime();
Clock myclock2;//调用默认构造函数
myclock2.showTime();
return 0;
}
委托构造函数
Clock::Clock(int hourh, int min, int sec) ://定义构造函数
hour(hourh), minute(min), second(sec) {//单冒号后 为初始化列表方式 形参赋值比赋值表达式效率更高
//无语句
}
Clock::Clock() : Clock(0,0,0) {}//默认构造函数 通过委托构造函数 保持一致性 调用定义的构造函数.
复制构造函数: 用已存在对象 构造新对象
未定义编译器也会生成默认复制构造函数,一一对应复制
=delete 不生成默认的复制构造函数
class类名 {
public :
类名(形参);//构造函数
类名(const 类名 &对象名);//复制构造函数
// …
};
类名::类(const 类名&对象名)//复制构造函数的实现
{ 函数体 }
//point::point(point &p){
x=p.x;
y=p.y;
}
strcpy(a,b)将字符b的内容copy到a内
未定义删除系统会自动生成一个析构函数,如同自动生成的构造函数。析构函数:
~类名()无参数表
point::~point(){
}
部件类构成组合类
组合类对象的构造:成员定义次序决定初始化次序;且先声明先构造;
组合类复制构造从后往前
例4-4 类的组合,线段(Line)类
//4_4.cpp
#include <iostream>
#include <cmath>
using namespace std;
class Point { //Point类定义
public:
Point(int xx = 0, int yy = 0) {
x = xx;
y = yy;
}
Point(Point &p);
int getX() { return x; }
int getY() { return y; }
private:
int x, y;
};
Point::Point(Point &p) { //复制构造函数的实现
x = p.x;
y = p.y;
cout << "Calling the copy constructor of Point" << endl;
}
//类的组合
class Line { //Line类的定义
public: //外部接口
Line(Point xp1, Point xp2);
Line(Line &l);
double getLen() { return len; }
private: //私有数据成员
Point p1, p2; //Point类的对象p1,p2
double len;
};
//组合类的构造函数
Line::Line(Point xp1, Point xp2) : p1(xp1), p2(xp2) {
cout << "Calling constructor of Line" << endl;
double x = static_cast<double>(p1.getX() - p2.getX());
double y = static_cast<double>(p1.getY() - p2.getY());
len = sqrt(x * x + y * y);
}
Line::Line (Line &l): p1(l.p1), p2(l.p2) {//组合类的复制构造函数
cout << "Calling the copy constructor of Line" << endl;
len = l.len;
}
//主函数
int main() {
Point myp1(1, 1), myp2(4, 5); //建立Point类的对象
Line line(myp1, myp2); //建立Line类的对象
Line line2(line); //利用复制构造函数建立一个新对象
cout << "The length of the line is: ";
cout << line.getLen() << endl;
cout << "The length of the line2 is: ";
cout << line2.getLen() << endl;
return 0;
}
结构体
struct student {
int num;
int age;
string name;
char sex;
};
联合体
#include <iostream>
using namespace std;
class ExamInfo {
private:
string name; //课程名称
enum { GRADE, PASS, PERCENTAGE } mode;//计分方式
union {
char grade; //等级制的成绩
bool pass; //只记是否通过课程的成绩
int percent; //百分制的成绩
};
public:
//三种构造函数,分别用等级、是否通过和百分初始化
ExamInfo(string name, char grade)
: name(name), mode(GRADE), grade(grade) { }
ExamInfo(string name, bool pass)
: name(name), mode(PASS), pass(pass) { }
ExamInfo(string name, int percent)
: name(name), mode(PERCENTAGE), percent(percent) { }
void show();
}
void ExamInfo::show() {
cout << name << ": ";
switch (mode) {
case GRADE: cout << grade; break;
case PASS: cout << (pass ? "PASS" : "FAIL"); break;
case PERCENTAGE: cout << percent; break;
}
cout << endl;
}
int main() {
ExamInfo course1("English", 'B');
ExamInfo course2("Calculus", true);
ExamInfo course3("C++ Programming", 85);
course1.show();
course2.show();
course3.show();
return 0;
}
实验4
#include<iostream>;
using namespace std;
enum Cpu_rank { p1 = 1, p2, p3, p4, p5, p6, p7 };
class CPU {
private:
int freq;
float voltage;
Cpu_rank rank;
public:
// void run();
// void stop();
CPU( int f, float v, Cpu_rank r) {//构造函数
rank = r;
freq = f;
voltage = v;
cout << "构造" << endl;
}
~CPU() { cout << "析构" << endl; }
//外部接口
int getfreq()const { return freq; }
float getvoltage()const { return voltage; };
Cpu_rank getrank()const { return rank; }
void setfreq(int f) { freq = f; };
void setrank(Cpu_rank r) { rank = r; };
void setvoltage(float v) { voltage = v; }
void run(){ cout << "run" <<freq<< endl; }
void stop() { cout << "stop" << endl; }
};
int main() {
CPU x(45, 450.2, p3);
int a;
x.run();
x.setfreq(a = 10) ;
x.run();
x.stop();
return 0;
}