c++的基本语法
如果你是一个掌握了其他编程语言的同学,那么c++的基础语法就比较简单了,特别是之前掌握了C#的同学,c++的语法就太容易理解了,java的也还可以
如果是初次了解编程的那么肯能就费点劲了。这里推荐线上菜鸟学习网站:https://www.runoob.com/cplusplus/cpp-arrays.html
数组
#include<iostream> using namespace std; #include<iomanip> using std::setw; int main() { int n[10];//n 是一个包含10个整数的数组 //初始化数组元素 for(int i=0;i<10;i++) { n[i] = i+100; } cout <<"Element"<<setw(13)<<"Value"<< endl; // 输出数组中每个元素的值 for ( int j = 0; j < 10; j++ ) { cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl; } return 0; }
变量
#include<iostream> using namespace std; /* * 变量 * 作用:给一段指令的内存空间起名,方便操作这段内容 * 语法:数据类型 变量名 = 初始值; * */ int main(){ int a = 10; cout << "a="<< a<<endl; return 0; }
常量
作用:用于记录程序中不可更改的数据
C++定义常量的两种方式
1)#define 宏常量:
#define 常量名 常量值
通常在文件上方定义,表示一个常量
2)const修饰的变量:
const 数据类型 常量名 = 常量值
通常在变量定义前加关键字const,修饰改变量为常量,不可修改
#include<iostream> using namespace std; // 常量的定义方式 //1. #define 宏常量 ,一般定义在文件头 //2. const修饰的变量,一般定义在函数体内部即可 //1. #define 宏常量声明,常量一旦修改就会报错 #define Day 7 int main(){ cout << "一周共有:" << Day << "天" << endl; //2. const修饰的变量 const int month = 12; cout << "一年有:" << month << "个月份" << endl; return 0; }
数据的输入 cin
#include<iostream> using namespace std; int main(){ //整型输入 int a = 0; cout << "请输入整型变量:"<<endl; cin >> a; cout << a<<endl; //浮点型输入 double d = 0; cout << "请输入浮点型变量:" << endl; cin >> d; cout << d << endl; return 0; }