变量与运算
变量声明
C++ 中的变量在使用前必须声明特定的数据类型。以下是基本数据类型:
基本变量声明
#include <iostream>
using namespace std;
int main() {
// Integer types
int age = 25;
long population = 1000000L;
short score = 95;
// Floating point types
float price = 19.99f;
double pi = 3.14159265359;
// Character types
char grade = 'A';
string name = "John Doe";
// Boolean type
bool isActive = true;
cout << "Age: " << age << endl;
cout << "Name: " << name << endl;
cout << "Grade: " << grade << endl;
cout << "Active: " << isActive << endl;
return 0;
}变量初始化
C++ 支持多种变量初始化方式:
初始化方法
#include <iostream>
using namespace std;
int main() {
// Copy initialization
int a = 10;
// Direct initialization
int b(20);
// List initialization (C++11)
int c{30};
int d = {40};
// Default initialization
int e; // Uninitialized (contains garbage value)
// Multiple variable declaration
int x = 1, y = 2, z = 3;
cout << "a: " << a << ", b: " << b << ", c: " << c << ", d: " << d << endl;
cout << "x: " << x << ", y: " << y << ", z: " << z << endl;
return 0;
}算术运算符
C++ 提供各种算术运算符进行数学计算:
算术运算
#include <iostream>
using namespace std;
int main() {
int a = 15, b = 4;
cout << "a = " << a << ", b = " << b << endl;
cout << "Addition: a + b = " << (a + b) << endl;
cout << "Subtraction: a - b = " << (a - b) << endl;
cout << "Multiplication: a * b = " << (a * b) << endl;
cout << "Division: a / b = " << (a / b) << endl;
cout << "Modulus: a % b = " << (a % b) << endl;
// Increment and decrement
cout << "\nIncrement/Decrement:" << endl;
cout << "a++ = " << a++ << " (post-increment)" << endl;
cout << "a = " << a << " (after post-increment)" << endl;
cout << "++a = " << ++a << " (pre-increment)" << endl;
return 0;
}赋值运算符
赋值运算符用于给变量赋值:
赋值运算
#include <iostream>
using namespace std;
int main() {
int x = 10;
cout << "Initial value: x = " << x << endl;
x += 5; // x = x + 5
cout << "After x += 5: x = " << x << endl;
x -= 3; // x = x - 3
cout << "After x -= 3: x = " << x << endl;
x *= 2; // x = x * 2
cout << "After x *= 2: x = " << x << endl;
x /= 4; // x = x / 4
cout << "After x /= 4: x = " << x << endl;
x %= 3; // x = x % 3
cout << "After x %= 3: x = " << x << endl;
return 0;
}常量
常量是初始化后不能修改的值:
常量声明
#include <iostream>
using namespace std;
int main() {
// Using const keyword
const int MAX_SIZE = 100;
const double PI = 3.14159;
const char GRADE = 'A';
// Using #define preprocessor
#define SPEED_OF_LIGHT 299792458
cout << "Max size: " << MAX_SIZE << endl;
cout << "PI: " << PI << endl;
cout << "Grade: " << GRADE << endl;
cout << "Speed of light: " << SPEED_OF_LIGHT << " m/s" << endl;
// This would cause a compilation error:
// MAX_SIZE = 200; // Error: cannot modify const variable
return 0;
}