C++初识
HelloWord
打开Visual Studio,创建新项目,左侧选择Visual C++
,选择空项目。
右键源文件,添加→新建项
编写一段helloWord代码
#include <iostream>
using namespace std;
int main()
{
cout << "hello word" << endl;
system("pause");
return 0;
}
main
是一个程序的入口,每个程序都必须有这么一个函数,有且仅有一个。
点击运行代码
变量、常量和关键字
单行注释: //描述信息
多行注释: /* 描述信息 */
变量的作用:给一段指定的内存空间起名,方便操作这段内存
语法 :数据类型 变量名 = 初始值;
#include <iostream>
using namespace std;
int main()
{
int a = 10;
cout << "a = " << a << endl;
system("pause");
return 0;
}
**常量的作用:**用于记录程序中不可更改的数据
C++定义常量的两种方式
- #define 宏常量:
#define 常量名 常量值
· 通常在文件上方定义,表示一个常量 - #const修饰的变量:
#const 数据类型 常量名 = 常量值
· 通常在变量定义前加关键字const,修饰该变量为常量,不可修改
关键字的作用:预先保留的单词(标识符)
*不要用关键字给变量或者常量起名称
*标识符只能由字母、数字、下划线组成
*第一个字符必须为字母或下划线
*标识符中字母区分大小写
数据类型
C++规定在创建一个变量或者常量时,必须要指定出相应的数据类型,否则无法给变量分配内存
整型
sizeof
实型(浮点型)
作用:用于表示小数
- 单精度float
- 双精度double
科学计数法
float f = 3e2 // f = 3*10^2
字符型
作用:字符型变量用于显示单个字符
语法: char ch = 'a'
#include <iostream>
using namespace std;
int main()
{
char ch = 'a';
cout << ch << endl;
cout << sizeof(char)<<endl;
cout << (int)ch << endl;
system("pause");
return 0;
}
字符串
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str1 = "runoob";
string str2 = "google";
string str3;
int len ;
str3 = str1;
cout << "str3 : " << str3 << endl;
str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;
len = str3.size();
cout << "str3.size() : " << len << endl;
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)