设为首页 加入收藏

TOP

1、C++基础知识代码笔记
2023-07-23 13:29:13 】 浏览:28
Tags:

C++ 课堂笔记(一)

说明:此笔记是学习于B站黑马程序员的C++视频所作的,感谢黑马程序员的教学;如有什么不足之处,望各位赐教。仅供学习。

第一个代码:书写hello world

#include<iostream>
using namespace std;

int main() {
	cout << "hello world" << endl;

	system("pause");
	return 0;
}


常量及变量

常量的定义方法有两种;
(1)宏常量:在main文件的上方定义。(此定义方法与C语言一样)如:#define week 7  (定义时不用分号)
(2)const修饰变量。如:const int money = 80;


变量的定义:数据类型 变量名 = 初始值;
点击查看代码
#include<iostream>
using namespace std;
//1.宏常量(在main文件上方定义)
#define Day 7


int main2() {
	//变量的定义: 数据类型 变量名 = 初始值;
	int a = 3;
	cout << "a=" << a << endl;
	
	//1.宏变量输出
	cout << "一周总共有 " << Day << " 天" << endl;

    //2.const修饰变量
	const int month=12;
	cout << "一年一共有 " << month << " 个月" << endl;

	system("pause");
	return 0;
}


数据类型

sizeof()统计数据类型所占内存大小

(1)整型:
short占内存空间为 2 ;int占内存空间为 4 ;long占内存空间为 4 ;long long占内存空间为 8

//整型
short a = 4;
int b = 3;
long c = 20488;
long long d = 37529075;
cout << "short类型所占内存空间为:" << sizeof(short) << endl;
cout << "int类型所占内存空间为:" << sizeof(int) << endl;

(2)浮点型(统计小数):
float占内存空间为 4 ;double占内存空间为 8

float f1 = 3.14f;//这里加f的原因是机器默认小数是double型,
		//double转换成float是低精度转换容易丢数据;
		//加上个 'f' 就是告诉编译器这个数是 float 类型的
double d1 = 3.1415;
cout << "f1 = " << f1 << endl;
cout << "d1 = " << d1 << endl;
cout << "float sizeof = " << sizeof(f1) << endl;
cout << "double sizeof = " << sizeof(d1) << endl;

(3)字符型:
变量只占内存1个字节

char ch = 'a';
cout << "sizeof(char) : " << sizeof(char) << endl;
cout << (int)ch << endl;//输出‘a’的ASCII码值;
ch = 65;//'A'的ASCII码值为65                注:大小写的a的ASCII码值相差32
cout << ch << endl;

(4)字符串型:
1、c风格字符串:char 变量名[] = "字符串值";(和c语言定义字符串一样)

char str1[] = "hello world";
cout << str1 << endl;
cout << str1[2] << endl;

2、string 变量名 = "字符串值";( 注:需加入头文件 #include )
#include<iostream>
using namespace std;
#include<string>  //注意后面是没有分号的

int main() {
	string str = "Hello world!";
	cout << str << endl;
}

(5)bool类型:
判断真假(1为真,0为假),占内存为1个字节;
注:java中是boolean;而c++中是bool。

bool flag = true;
cout << flag << endl; // 1

flag = false;
cout << flag << endl; // 0

cout << "size of bool = " << sizeof(bool) << endl; //1


cin:用于从键盘获取数据

语法: cin >> 变量;

string str2;
cout << "请输入字符串变量:" << endl;
cin >> str2;
cout << str2 << endl;
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇在 C# CLR 中学习 C++ 之了解 ext.. 下一篇IP(IPv4)地址ABC划分及私有地址

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目