C++编程基础一 01-我的第一个项目
1 // 01-第一个项目.cpp: 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" //自己创建的文件。 header .h结尾的都是头文件。 5 #include <iostream> //系统内置的文件。#include 预处理指令,把系统内置的iostream(输入输出流)先引入进来。cout属于iostream 6 //using namespace std; //命名空间也可以放在这里,所有的函数都可以使用。 7 8 9 void MyFunction(); //与C#不通的是,如果自定义的函数在main函数之后,main函数想调用自定义函数则需要在main函数之前先声明自定义函数。 10 void ShowMonth(); 11 //function 只有动态连接库不需要main()函数,需要别人去调用的。 12 int main() //main函数(function)是程序的入口函数,int是函数的返回值 ()内为参数 {}内是函数体 13 { 14 using namespace std; //使用std命名空间 standard标准的命名空间,命名空间是对文件中不同的功能进行分类、 15 //using std::cout; 16 //using std::cin; 17 //using std::endl;//由于std命名空间中有上百个函数,我们又只需要用几个,有点浪费,所以可以单独引用std中的函数。 18 19 std::cout << "您好";//如果没有在函数的开始写using name std语句,可以单独std::cout使用cout函数。 20 std::cout << std::endl; 21 cout << "你好"; //标准输出。类似C#的console.writeline; 22 cout << endl; //end line? 行的结束,换行。 23 cout << "我开始学程序了" << endl; // <<可以接着用,endl就可以放在语句的前面或者后面,不用单独写一行。 24 cout << endl << "我真的开始学程序了"; 25 cout << "\n" << "真的\n真的"; //"\n"可以放在任意位置来实现字符串换行。 26 printf("我的年龄是%d", 18);//C的写法 27 printf("我的年龄是%s", "18");//C的写法 无法自己识别输出的类型,需要%占位符后指定类型,比较麻烦。 28 cin.get(); //类似C#中的Console.readkey(); 29 MyFunction(); 30 return 0; //返回值为0 31 32 //Ctrl+K,Ctrl+F 格式化代码。 33 //代码中高亮的都是C++中的关键字 34 35 } 36 37 //————————————————————————练习————————————————————————— 38 //1.下面语句做什么的? 39 //using namespace std 40 //答:引入standard标准命名空间,命名空间将文件中的函数进行分类,引入std后便可访问std中的函数。包含cout(输出)、endl和cin函数。 41 42 //2.打印HelloWorld 并换行。 43 void MyFunction() 44 { 45 using namespace std; 46 cout << "Hello Word!"<<endl; 47 cout << "Hello Word!\n" ; 48 ShowMonth(); 49 50 cin.get(); 51 52 //std::cin.get();//或者单独引用 命名空间和函数名之间用:: 53 } 54 55 //3.什么情况下,函数中可以不适用return 56 //答:在函数没有定义返回值的情况下,void。 57 58 //4.让用户输入他的年龄,并显示这个年龄包含多少个月。 59 void ShowMonth() 60 { 61 using namespace std; 62 int age; 63 cout << "请输入你的年龄!"; 64 cin >> age; //记录输入的年龄到age中 65 int months = age * 12; 66 cout << "你在地球上生存了" << months << "天!"; 67 cin.get(); 68 }