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实际存储并非-50cout << 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():注意breakswitch (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";elsecout << "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=0cout << 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);//浮点数绝对值fabsreturn 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;elsey = 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;elsereturn 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;elsereturn 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;
}

c++practice相关推荐

  1. HDU1089-1096 A+B for Input-Output Practice 系列问题(输入输出格式练习)

    HDU1089 A+B for Input-output Practice (1) 问题描述:每行输入一对整数a和b,每行对应输出a与b的和. Sample Input 1 5 10 20 Sampl ...

  2. Programmer of Practice Manual

    这是我以前再读研究生的时候写的东东,希望搞计算机的同学,教计算机本科生学习技术的文章(非算法类) 粘在这里纪念一下. 大一寒假 结构化编程基础: 图书:<How to C> 实践过程:完成 ...

  3. Database design best practice(1):关于primary key及其它

    1. The job of the primary key is to uniquely identify records, not to store business data ; any use ...

  4. 《Git in Practice》作者访谈:关于Git的八个问题

    Mike McQuaid的著作<Git in Pratice>是一份具有动手实践性的指导,它从实践性的角度介绍了Git,提供了超过60种在操作Git库时会使用到的技巧和命令,并且为有经验的 ...

  5. Remoting Practice Sample

    Remoting Practice Sample 这两天研究了一下Remoting, 改了MSDN 的例子. 那个例子不是很方便. 我做了如下改进: 整个sample做成一个solution 用了wi ...

  6. ATPG Practice ATPG Practice II

    文章目录 General ATPG Flow ATPG DRC example clock to data ATPG setting delay test的两种方法 single capture do ...

  7. DFT实训教程笔记2(bibili版本)- Scan synthesis practice

    文章目录 Scan synthesis practice 本博文是博主记录DFT实训教程的笔记版本,此笔记并没有对所有的知识进行记录,仅仅以自身的认知水平,来记录了一些部分笔记并加上了自己的理解. S ...

  8. Best practice for JVM Tuning[转]

    原文地址:https://backstage.forgerock.com/knowledge/kb/article/a35746010 JVM tuning considerations Before ...

  9. phrases practice_七年级短语、固定搭配练习题Phrases practice for Grade seven

    Phrases practice for Grade seven( 英汉汉英互译 ) Be______with: 小心对待 从现在起: _________________ 匆忙: __________ ...

  10. 盖瑞解剖学: 临床实践的解剖学基础 Gray‘s Anatomy: The Anatomical Basis of Clinical Practice 高清英文原版

    盖瑞解剖学: 临床实践的解剖学基础 Gray's Anatomy: The Anatomical Basis of Clinical Practice PDF 获取ebook<<<& ...

最新文章

  1. stm32跑马灯实验
  2. linux畸形文件夹,Linux下简单的缓冲区溢出
  3. Anaconda:成功解决Anaconda下载时速度超慢(conda下载慢)的几种方法图文教程
  4. ios15 LJScrollPageVC第三方框架的使用
  5. 使用rpm包升级ntpd服务_服务器准备升级,小程序将暂停使用
  6. 浙江使用计算机的用量,现在全世界计算机的使用量是多少
  7. 动态语言会淘汰静态语言吗?
  8. 项目分层思路——管家婆
  9. Windows内核结构
  10. cmd命令行激活win7
  11. VMX(2) -- VMCS理解
  12. FastFCN: Rethinking Dilated Convolution in the Backbone for Semantic Segmentation
  13. DVDFab Virtual Drive是一套虚拟DVD/蓝光光驱模拟器。虚拟光驱。
  14. android 有关毫秒转时间的方法,及时间间隔等
  15. 黑客攻防技术宝典(十八)
  16. 逗号表达式java_9_三目运算符和逗号表达式
  17. 史上最全面的《软件工程》笔记—— 期末不挂科就看这一篇
  18. Markdown使用方法、常用技巧汇总
  19. 【职场宝典】之二:样品管理员,你的工作无可替代
  20. 数据结构教程(Java语言描述)前两章总结

热门文章

  1. Linux从入门到实战 ---- 磁盘分区
  2. 编程篇 - esp 8266物联网开发板 - 给板子编写并且烧录程序, 整点有意思的效果
  3. React Native Camera的新手教程
  4. Nacos服务---主流配置中心对比
  5. 手势检测及手掌质心的运动轨迹(opencv)
  6. Halcon识别金属上的雕刻字符
  7. Ubuntu安装Caffe .build_release/tools/caffe: error while loading shared libraries: libcudart.so.8.0
  8. 7.消费者的确认机制
  9. lsdyna批处理求解工具使用
  10. tomcat宕机自动重启和每日定时启动tomcat