C++_初识C++和数据类型

C++基础

初识C++

1.第一个C++程序

#include <iostream>
using namespace std;

int main()
{
	cout<<"Hello World"<<endl;
	
	return 0;
}

2.注释

#include <iostream>
using namespace std;

int main()
{
	//第一个C++程序 
	cout<<"Hello World"<<endl;
	/*
	输出Hello World 
	*/ 
	return 0;
}

3.变量

int a = 10; //a是一个整型变量

4.常量

#include <iostream>
using namespace std;

#define pi1 3.14 //宏常量 

int main()
{
    const float pi2 = 3.14f; //利用关键字修饰变量,实际为常量 
    
	cout<<pi1<<endl;
	cout<<pi2<<endl;
	
	return 0;
}

5.关键字

6.标识符命名规则

  • 标识符不能是关键字
  • 标识符由数字、下划线、字母组成
  • 标识符只能是下划线或字母开头
  • 标识符区分大小写

数据类型

给变量分配合适的内存空间

1.整型

  • 短整型short
  • 整型int
  • 长整型long
  • 长长整型long long

2.sizeof关键字

  • 统计数据类型所占内存空间的大小
  • sizeof(数据类型/变量)

3.实型(浮点型)

  • 单精度float
  • 双精度double
#include <iostream>
using namespace std;

int main()
{
    float f1 = 3.14f; 
    double d1 = 3.14;

    float f2 = 3e2; //3*10^2 
    float f3 = 3e-2; //3*0.1^2 
    
	cout<<f2<<endl;
	cout<<f3<<endl;
	
	return 0;
}

4.字符型

char ch = 'a';
  • 使用单引号,包含一个字符
  • 单引号中只能写单个字符
  • 内存中存放的是单个字符的ASCII码
#include <iostream>
using namespace std;

int main()
{
    int a = 10;
    float b = 3e2;
    char ch = 'a';
    
	cout<<sizeof(short)<<endl;  //2 
	cout<<sizeof(a)<<endl;	//4
	cout<<sizeof(long)<<endl;  //4
	cout<<sizeof(long long)<<endl;  //8
	cout<<sizeof(b)<<endl;  //4
	cout<<sizeof(double)<<endl;  //8
	cout<<sizeof(ch)<<endl; //1

	return 0;
}

5.转义字符

  • 换行\n
  • 反斜杠\
  • 水平制表\t

6.字符串型

#include <iostream>
using namespace std;
#include <string>

int main()
{
    //C语言
	char str1[] = "Hello World"; 
	cout<<str1<<endl;
	//C++,必须使用头文件 
	string str2 = "Hello World";
	cout<<str1<<endl;

	return 0;
}

7.bool类型

  • true对应1
  • false对应0
#include <iostream>
using namespace std;
#include <string>

int main()
{
    bool flag1 = true;
	bool flag2 = false; 
	
	cout<<flag1<<endl;
	cout<<flag2<<endl;
	
	cout<<sizeof(string)<<endl;
	cout<<sizeof(flag1)<<endl;
	
	return 0;
}

8.数据的输入

#include <iostream>
using namespace std;

int main()
{
    int a; 
	
	cout<<"请输入整型变量a的值:"<<endl;
	cin>>a;
	cout<<"整型变量a="<<a<<endl;
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值