c/c++基础操作笔记

C

安装

codeblocks文本编译器,集成MinGW

下载地址:Code::Blocks - Code::Blocks

创建项目

画个三角形

printf("    /|\n");
printf("   / |\n");
printf("  /  |\n");
printf(" /___|\n");

注释

 /* this prints out text. */
//  this also comments too,

变量

创建变量

char characterName[] = 'Tom';// we going to tell program this variable is a char charname ,and we still want more charactername save in this variable, so we use []
char characterAge = 35;

在printf中使用

printf("There once was a man named %s\n",characterName);// here %s,%i is a placehholder占位符
printf("He is %i years old.\n",characterAge);

内存地址

所有值都有一个地址储存在内存中,C需要使用地址访问这些值

int age =30;
double gpa = 3.4;
char grade = 'A';
printf("age:%p\ngpa:%p\ngrade:%p\n",&age,&gpa,&grade); // print out the memory address %p:指针

数据类型

基础数据类型 :数字(整形, 浮点类型, 双精度类型); 字符(char)

其他数据类型: 数组(char variablename[] ),指针

<!--字符串的存储是基于字符的数组-->

int age = 40;
double gpa = 3.; // float
double gpa_1 = 4.5;
char grade = 'a'; // a character
char phrase[] = "sherry";

指针

物理内存地址

案例:

int age = 10;
int * pAge = &age; //this pointer variable stories an other variable address.
print("%p",&age);//&age is a pointer,物理内存地址
printf("pAge:%p\n",pAge);/* deference a pointer 取消引用指针,抓取实际的值;use * 取消指针,将指针变为获取实际的值*/
printf("* pAge : %d\n",* pAge); // 实际值
printf("* &age : %d\n",* &age); // 实际值
printf("& * &age: %d\n",& * &age); // 物理地址

数学运算

基本数学运算
printf("%f\n",5.0 + 4.5);
printf("%f\n",5.0 / 4.5);
printf("%f\n",5.0 * 4.5);
printf("%f\n",5.0 - 4.5);
逻辑运算
if (3 > 2 || 2 > 5){ // ||为或的意思
        printf("3 > 2 || 2 > 5 is True.\n");}
if (3 > 2 && 2 > 5){ // &&为和的意思
        printf("3 > 2 && 2 > 5 is True.\n");}
if (3 != 2){
        printf("3 != 2 True.\n");}
if (!(3 == 2)){
        printf("!(3 = 2) True.\n");}
整形+浮点型返回浮点型
print("%f\n",5 + 4.5);
当数据类型和%不匹配出错

结果应该是整形,但c代码要求“严格”,导致%f仅能输出浮点型,并且程序没有报错。

常量

无法重新赋值的变量

const int num = 5;
printf("%d\n",num);
num = 8; // program error

数组

创建,访问,重定义

int luckyNumbers [] = {4,8,1,15,53,26}; //use , to seperate the number
// int luckyNumbers[10]; // can save 10 number
luckyNumbers[0] = 200; 
printf("%d\n",luckyNumbers[2]); // access to number use index
printf("%d\n",luckyNumbers[0]);

二维数组

 /*二维数组到多维数组 和嵌套*/
int nums[3][2] = {//数组的宽和高
                        {1,2},
                        {3,4},
                        {5,6}
                        };
​
int i,j;
for(i = 0; i < 3; i++){
    for(j = 0;j < 2;j++){
            printf("%d,",nums[i][j]);
        }
        printf("\n");
    };

数据结构

创建案例:

struct Student{ //基本结构模板
    char name[50];
    char major[50];
    int age;
    double gpa;
};

调用案例:

struct Student student1;
student1.age = 22;
student1.gpa ==3.2;
strcpy(student1.name,"jim");//不能直接传入值,c中字符串类似数组,无法用=赋值,函数将字符串copy并且传入student1.name中
strcpy(student1.major,"business");

if 条件

案例:

int max(int num1, int num2){
    int result;
    if (num1 > num2){
        result = num1;
    }else{
        result = num2;
    }
    return result;
}

案例:

int max(int num1, int num2, int num3){
    int result;
    if (num1 >=num2 && num1 >= num3 ){
        result = num1;
    }else if(num2 >= num1 && num2 >= num3){
        result = num2;
    }else{
        result = num3;
    }
    return result;
}

case 条件

 switch(grade){ // 对一个事件进行划分
    case 'A':
        printf("You did great!");
        break;
    case 'B':
        printf("You did alright!");
    case 'C':
        printf("You did poorly");
    case 'D':
        printf("You did poorly");
    case 'E':
        printf("you did very bad!");
    case 'F':
        printf("You failed!");
    default: // 相当于else
        printf("Invalid Grade");
    }

while

  int index = 1;
    while(index <= 5 ){
        printf("%d\n",index);
        index++;
    }//检查条件决定本次是否运行
​
    do{
        printf("%d\n",index);
        index++;
    }while(index <= 5);//运行再决定下一次是否继续

for 循环

int luckyNumber[] = {1,5,6,4,20,32};
for(i = 0; i < 6; i++){// i初始值,循环条件值,i的增减
    printf("%d\n",luckyNumber[i]);
    };

函数

函数用于执行某个特定功能块。注意在c中main函数为特殊函数,每次我们运行c程序,c函数中的所有代码将会自动运行。

参数:函数之间传递数据(形参,实参)。

写一个函数

案例:

void sayHi() // void 意味着这个函数没有return数据
{
    printf("Hello User");
}

案例:

#include <stdio.h>
#include <stdlib.h>
​
double cube(double num); // 在main中调用,必须在main之前创建
​
int main() {
    printf("Answer: %f",cube(8.5));
    return 0;
}
​
double cube(double num) /*must create before main,
                            so that main konw this function or write its head line before main*/
{
    double result = num * num * num;
    return result; // make us leave this function
    printf("here we are , below the return");//return之后,不运行
}
​

运行流程

printf

函数:向运行窗口输出文字

反斜杠:注释紧跟的特殊字符为文本,无需编程处理

printf("Hello\"World");

格式说明符:告诉c,我们打算打印一些特殊的字符

printf("my favorite %s is %d","number",500);

%f : float,double

%c : a character

数学运算

指数函数
printf("%f\n",pow(2,3));
平方根函数
printf("%f\n",sqrt(36));
四舍五入
printf("%f\n",ceil(36.542)); // 四舍五入
printf("%f\n",floor(36.542)); // 取较小

scanf获取用户输入

注意:输入中的空格会让c以为你已经完成输入

案例:

double gpa;
printf("Enter your gpa: ");
scanf("%lf",&gpa); // use scan ect function need use &, pointer needed.
printf("you grade is %f ",gpa);

案例:

char name[20]; // 20 is telling c how long i want this string
printf("enter your name:");
scanf("%s",name);
printf("you name is %s",name);

fgets

获取整行输入,不论行内包含空格,数字,文本种种

char name[20]; 
printf("enter your name:");
fgets(name,20,stdin); // 20 limit string length,standard input.avoid users input 100w char makes buffer overflow
printf("you name is %s",name);

文件

写入文件:

/* create ,adding new file
        创建文件本质创建一个指向我们物理文件的指针*/
FILE * fpointer = fopen("employees.txt","w");
//you can also write some css,html file
// filename(url),mode(tell c what we want to do with that file)
/*three mode: r     read
              w     write
              a     append*/
fprintf(fpointer,"Jim,Salesman\nsherry,Acounting"); // write info into file
fclose(fpointer);

读取文件:

char line[255];
FILE * fpointer = fopen("employees.txt","r");
/* read line one by one */
fgets(line,255,fpointer);//read the first line,储存位置,储存长度,文件
fgets(line,255,fpointer);// get the second line
printf("%s",line);
fclose(fpointer);

C++

注释

// 单行注释
/*多行注释*/

变量

创建

类似C语言,数据类型 变量名称

string characterName = "sherry";
int characterAge;
characterAge = 20;

使用:

cout << "There once was a man named "<< characterName << endl;
cout << "He was "<< characterAge <<" years old" << endl;

数据类型

基本数据类型:数字(int,float,double),文本(char,string),布尔类型

char grade = 'A';
string phrase = "Giraffe Academy";
int age = 50;
//float
//double could store more number
bool isMale = true;
​
cout << grade << endl;
cout << "asdf" << endl; // constant 常量,无需修改

字符串

创建,索引,重新赋值

string phrase = "sherry catholic";
cout << phrase[0] << endl; //第0索引处字符
phrase[0] = 'F';

函数: length, find, substr

cout << phrase.length() << endl; //字符串长度
cout << phrase.find("catholic",0) << endl;
      // 找到这个字符串catholic在phrase中的位置,并且返回第0个索引
cout << phrase.substr(8,3) << endl;
     // 从第几个位置开始抓起,抓多少个字符

数字

数学运算

cout << 5 + 7 << endl;
cout << 5 - 7 << endl;
cout << 5 * 7 << endl;
cout << 5 / 7 << endl;
cout << 10 % 3 << endl; //余数

整数除整数返回浮点数导致错误

cout << 10 / 3 << endl; //output int ,3
cout << 10.0 / 3.0 << endl; // output double, 3.333...
数学函数
# include <cmath> //we want to use some cmath function
​
cout << pow(2,5) << endl;
cout << sqrt(36.9) << endl;
cout << round(4.6) << endl;
cout << ceil(4.1) << endl;
cout << floor(4.6) << endl;
cout << fmax(4,5) << endl;
cout << fmin(8,7) << endl;

指针

指针,一种存储物理内存地址的数据类型

int age = 19;
cout << &age; //access to pointer

创建指针,访问指针

    int age = 19;
    int * pAge = &age;
    double gpa = 2.7;
    double * pGpa = &gpa; //pointer type should be same as value
    cout << &age << endl;
    cout << pAge <<endl; //pointer
    cout << * pAge << endl; //value
    cout << & * pAge << endl;

数组

int luckyNums[20] = {4,5,7,8,23,67,42};
            // just tell c++ how many place you want,but it doesn't need 20 numbers in the array
​
luckyNums[0] = 23; //修改元素值
cout << luckyNums[0] << endl;
​
luckyNums[10] =100;
cout << luckyNums[10] << endl;

二维数组和嵌套循环

int numberGrid[3][2] = {    {1,2},
                            {3,4},
                            {5,6},
                            } ;
​
    //nested for loop 嵌套for循环
for(int i = 0;i < 3; i++){
    for(int j = 0; j < 2; j++){
        cout << numberGrid[i][j];
        }
    cout << endl;
    }

if 条件

逻辑运算: && , ||(A或B成立即成立)

bool isMale = false;
bool isTall = true;
​
if(isMale && isTall){
        cout << "you are a tall male";
    }else if(isMale && !isTall){
        cout << " you are a short male";
    }else if(!isMale && !isTall){
        cout << "you are not male and not tall";
    }else{
        cout << "you are tall but not male.";
    };

switch

switch(dayNum){
    case 0 :
        dayName = "Sunday";
        break;
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    default:
        dayName = "Invalid Day Number";
        break;
    };

while

int index = 1;
    while(index <= 5){
        cout << index << endl;
        index ++;
    }
int index = 6;
do {
    cout << index << endl;
 }while(index <=5);

for

for(int i = 1; i <=5 ; i++){
        cout << "times " << i << endl;
    }

写一个指数运算函数

int power(int baseNum,int powNum){
    int result = 1;
​
    for(int i = 0; i < powNum;i++){
        result = result * baseNum;
    }
​
    return result;
}

函数

写一个函数

返回类型:void(不返回数据),double(返回double数据)

参数:形参与实参

void sayHi(string name);// use in main, must create before the main
double cube(double num){
/*caculate the number and return result*/
    double result = num * num * num;
    return result; //return number to main
}
​
int main(){
    cout << "Top" << endl;
    sayHi("sherry"); //call the function
    cout << "bottom" << endl;
​
    double answer = cube(5.0);
    cout << answer;
    return 0;
}
​
void sayHi(string name){
    cout << "Hello "<< name << endl;
}

获取用户输入

获取数字,字符输入:

double age;
cout << "enter your age: "; // cout << means c out
cin >> age; // cin >> means c ,input

获取文本输入:

getline(cin,name); //get string of text

类与对象

类就像一种数据类型,象征实物

对象是基于类创建的实例

class Book{
public:
    string title;
    string author;
    int pages;
    Book(string name){//constructor 构造函数,everytime you create the instance it will run
        cout << "Createing object. "<< name << endl;
    }
};
Book book1("harry potter");
book1.title = "Harry Potter";
book1.author = "JK Rowling";
book1.pages = 500;
​
cout << book1.pages;

使用构造函数初始化属性:

class Book{
public:
    string title;
    string author;
    int pages;
​
    Book(){
    title = "no title";
    author = "no author";
    pages = 0;
    }//multiply ways for user use.
​
    Book(string aTitle, string aAuthor, int aPages){//constructor 构造函数,everytime you create the instance it will run
    title = aTitle;
    author = aAuthor;
    pages = aPages;
    }
};
Book book1("harry potter","JK Rowling",500);
Book book2("business","WuJun",200);
Book book3;
​
cout << book1.pages << endl;
cout << book2.author << endl;
cout << book3.title << endl;

公开和私有

属性,类,方法属于私有时,只能被当前所在的类访问到。这意味着用户不能随意将奇奇怪怪的评价塞入类的属性中。

class Movie{
​
private:
    string rating;
public:
    string title;
    string director;
​
    Movie(string aTitle, string aDirector, string aRating){
        title = aTitle;
        director = aDirector;
        setRating(aRating);
    }
​
    void setRating(string aRating){
        if(aRating == "G" || aRating == "PG-13"||aRating =="R"||aRating =="NR"){
            rating = aRating;}else{
            rating = "NR";}
    }
​
    string getRating(){
        return rating;}
};
int main(){
    Movie avengers("The Avengers","Joss Whedon","rg-13");
    cout << avengers.getRating();//访问获取
    avengers.setRating("dog");    //访问设置值
    return 0;
}

继承

父类,子类,重写

子类可以继承调用父类的方法,或者重写父类的方法

class Chef{
    public:
        void makeChicken(){
        cout << "The chef makes yummy chicken" << endl;
        }
    };
​
class ItalianChef: public Chef{ //子类
    public:
        void makePatsa(){
        cout << "The chef makes pasta" << endl;
        }
        void makeChicken(){
        cout <<"The chef makes chicken parm" << endl; //对父类的重写
         }
    };
int main(){
    Chef chef;
    ItalianChef chef2;
​
    chef.makeChicken();
    chef2.makeChicken();
    return 0;
}

注:

最近找工作发现好多要求C/C++的,被迫回来补课了~~~QAQ

跟b站视频学的,链接:【C\C++系列课程】【联合出品】哈佛大学CS系列课程,油管500粉丝,谷歌高级工程师,GitHub项目排名第一!!!| 数据结构 操作系统 计算机组成原理

由于C,C++有很多类似的地方,可以先学C,快速浏览笔记尝试代码学会C++的基本操作。笔记是md文档,百度网盘可自取,链接:通过网盘分享的文件:cc++基础知识
链接: https://pan.baidu.com/s/19nP-xtJD-MGNDXcrUTnmCA 提取码: 3j3d

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值