您的位置:首页 > 编程语言 > C语言/C++

<3>C++ Primer字面值常量

2017-09-22 22:42 274 查看

字面值常量

1.整数字面值

简单来说字面值常量就是直接输出或者定义的常数。
如:
#include<iostream>

int main()
{
std::cout << 2 <<std::endl;
system("pause");
return 0;
}


正常情况下输出的常量为十进制,我们还可以在输出的数字前添加一个0,或者0x将数字以八进制或16进制表示。

#include<iostream>

int main()
{
std::cout << 14 <<std::endl;//14
std::cout << 014 << std::endl;//12
std::cout << 0x14 << std::endl;//20
std::cout << 0x14L << std::endl;
std::cout << 10u << std::endl;
system("pause");
return 0;
}



此时字面值常量默认为int或者long类型。

在数字后面加u表示无符号类型,加上L表示long类型。

2.浮点字面值

include<iostream>

int main()
{
//浮点字面值默认类型为double
std::cout << 3.1415926 <<std::endl;//3.1415926 double类型
std::cout << 3.1415926f << std::endl;//3.1415926 float类型
std::cout << 3.1415926L << std::endl;//3.1415926 long double类型
//科学计数法
std::cout << 3.1415926E2 << std::endl;//3.1415926*10^2
std::cout << 3.1415926e-2 << std::endl;//3.1415926*10^-2
return 0;
}



3.bool字面值

#include<iostream>

int main()
{
std::cout << true << std::endl;//1
std::cout << false << std::endl;//0
std::cout << (true && false)<<std::endl;//0
std::cout << (true || false) << std::endl;//1
system("pause");
return 0;
}

4.字符字面值

#include<iostream>
#include<wchar.h>
#include<stdlib.h>
#include<locale.h>

int main()
{
//默认为char类型
std::cout << 'A' << std::endl;//A
std::cout << L'中' << std::endl;//20013
setlocale(LC_ALL, "chs");
wprintf(L"%c\n", L'中');//中,L表示宽字符型
//C/C++中输出中文,需要加入setlocale函数才行。
return 0;
}


5.打印字符串

在C++是可以直接输出字符串的。
如:
int main()
{
std::cout << "hello world!" << std::endl;
return 0;
}


1>转译符'\'

有很多字符是不能直接输出的,如'\n',' " ','\',此时我们就需要通过添加转义符来输出:'\\n'.

int main()
{
//std::cout << ""hello world!"" << std::endl;//报错
std::cout << "\"hello world!\"" << std::endl;//"hello world!"
std::cout << "D:\\dd\\data" << std::endl;//D:\dd\data

//转义符的本质是将他后面的字符按照ACSLL码转换
//如\n的含义是换行,在ACSLL编码中n为10(十进制)
//'\'后面只能跟8进制或者16进制
std::cout << "2\nM" << std::endl;//2换行M
std::cout << "\062\012\115" << std::endl;//2换行M
std::cout << "\x032\x00a\x04d" << std::endl;//2换行M
return 0;
}


2>中文字符串
#include<iostream>
#include<wchar.h>
#include<stdlib.h>
#include<locale.h>

int main()
{
//标准输出也能输出中文字符串,但是char实际是为英文准备的
//在转义的过程中可能会出错,同时也会加大工作量
std::cout << "普通字符串" << std::endl;//普通字符串
//无法直接输出宽字符
std::cout << L"宽字符" << std::endl;//008ECA64
setlocale(LC_ALL, "chs");
wprintf(L"%ls\n", L"宽字符");//宽字符
return 0;
}


3>字符串的连接
int main()
{
//当字符串太长需要另起一行时:
std::cout << "C++ is the best "
"language in the world." << std::endl;
//使用'\'时,下一行不能有空格,否则会将空格一块输出
std::cout << "C++ is the best \
language in the world." << std::endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  函数 扩展 c语言