C
#include<stdio.h>
#include<math.h>
int main()
{
double x, y;
scanf("%f,&x"); // 输入一个双精度浮点数,并将其存储在变量 x 中
if (x >= 0)
{
y = sqrt(x); // 如果 x 大于等于 0,则计算平方根并将结果存储在变量 y 中
}
if (x < 0)
{
y = pow(x + 1, 2) + 2.0 * x + 1.0 / x; // 如果 x 小于 0,则进行一系列数学计算,并将结果存储在变量 y 中
}
printf("f(%f) = %f", x, y); // 打印函数值 f(x)
return 0;
}
C++
#include <iostream>
#include <cmath>
int main()
{
double x, y;
std::cout << "Enter a number: ";
std::cin >> x;
if (x >= 0)
{
y = sqrt(x);
}
else
{
y = pow(x + 1, 2) + 2.0 * x + 1.0 / x;
}
std::cout << "f(" << x << ") = " << y << std::endl;
return 0;
}
局部变量
在函数或一个代码块内部声明的变量。
只能被函数内部或者代码块内部的语句使用:
#include <iostream>
using namespace std;
int main ()
{
// 局部变量声明
int a, b;
int c;
// 实际初始化
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
全局变量
在所有函数外部定义的变量(通常是在程序的头部)。
全局变量的值在程序的整个生命周期内都有效
定义常量
在 C++ 中,有两种简单的定义常量的方式:
- 使用 #define 预处理器:
#include <iostream>
using namespace std;
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}
- 使用 const 关键字:
#include <iostream>
using namespace std;
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}
C++ 修饰符类型
C++ 允许在 char、int 和 double 数据类型前放置修饰符
数据类型修饰符:
signed:表示变量可以存储负数。对于整型变量来说,signed 可以省略,因为整型变量默认为有符号类型。
unsigned:表示变量不能存储负数。对于整型变量来说,unsigned 可以将变量范围扩大一倍。
short:表示变量的范围比 int 更小。short int 可以缩写为 short。
long:表示变量的范围比 int 更大。long int 可以缩写为 long。
long long:表示变量的范围比 long 更大。C++11 中新增的数据类型修饰符。
float:表示单精度浮点数。
double:表示双精度浮点数。
bool:表示布尔类型,只有 true 和 false 两个值。
char:表示字符类型。
wchar_t:表示宽字符类型,可以存储 Unicode 字符。
修饰符 signed、unsigned、long 和 short 可应用于整型,signed 和 unsigned 可应用于字符型,long 可应用于双精度型。
这些修饰符也可以组合使用,修饰符 signed 和 unsigned 也可以作为 long 或 short 修饰符的前缀。例如:unsigned long int。
#include <iostream>
using namespace std;
/*
* 这个程序演示了有符号整数和无符号整数之间的差别
*/
int main()
{
short int i; // 有符号短整数
short unsigned int j; // 无符号短整数
j = 50000;
i = j;
cout << i << " " << j;
return 0;
}
C++ 中的类型限定符
-
const const 定义常量,表示该变量的值不能被修改
-
volatile 修饰符 volatile 告诉该变量的值可能会被程序以外的因素改变,如硬件或其他线程
-
restrict 由 restrict 修饰的指针是唯一一种访问它所指向的对象的方式。只有 C99 增加了新的类型限定符 restrict
-
mutable 表示类中的成员变量可以在 const 成员函数中被修改
-
static 用于定义静态变量,表示该变量的作用域仅限于当前文件或当前函数内,不会被其他文件或函数访问
-
register 用于定义寄存器变量,表示该变量被频繁使用,可以存储在CPU的寄存器中,以提高程序的运行效率
mutable 实例
class Example {
public:
int get_value() const {
return value_; // const 关键字表示该成员函数不会修改对象中的数据成员
}
void set_value(int value) const {
value_ = value; // mutable 关键字允许在 const 成员函数中修改成员变量
}
private:
mutable int value_;
};
static 实例
void example_function() {
static int count = 0; // static 关键字使变量 count 存储在程序生命周期内都存在
count++;
}
register 实例
void example_function(register int num) {
// register 关键字建议编译器将变量 num 存储在寄存器中
// 以提高程序执行速度
// 但是实际上是否会存储在寄存器中由编译器决定
}