Skip to content

L2_07 数学函数

一、绝对值函数 (abs)

1.1 语法

cpp
int abs(int x);
long abs(long x);
long long abs(long long x);

1.2 示例

cpp
#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
    int a = -5;
    cout << abs(a) << endl;  // 输出 5
    
    long b = -123456789L;
    cout << abs(b) << endl;  // 输出 123456789
    
    return 0;
}

二、平方根函数 (sqrt)

2.1 语法

cpp
double sqrt(double x);

2.2 示例

cpp
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    double x = 16.0;
    cout << sqrt(x) << endl;  // 输出 4.0
    
    double y = 2.0;
    cout << sqrt(y) << endl;  // 输出 1.41421...
    
    return 0;
}

三、最大值函数 (max)

3.1 语法

cpp
int max(int a, int b);
double max(double a, double b);

3.2 示例

cpp
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int a = 10, b = 20;
    cout << max(a, b) << endl;  // 输出 20
    
    double x = 3.14, y = 2.71;
    cout << max(x, y) << endl;  // 输出 3.14
    
    return 0;
}

四、最小值函数 (min)

4.1 语法

cpp
int min(int a, int b);
double min(double a, double b);

4.2 示例

cpp
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int a = 10, b = 20;
    cout << min(a, b) << endl;  // 输出 10
    
    double x = 3.14, y = 2.71;
    cout << min(x, y) << endl;  // 输出 2.71
    
    return 0;
}

五、随机数函数 (rand/srand)

5.1 rand 函数

  • 返回一个随机整数
  • 范围:0 到 RAND_MAX(通常是 32767)

5.2 srand 函数

  • 设置随机数种子
  • 通常使用时间作为种子

5.3 示例

cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    // 设置随机数种子
    srand(time(0));
    
    // 生成随机整数
    int random_num = rand();
    cout << "随机数: " << random_num << endl;
    
    // 生成指定范围的随机数 (0-99)
    int range = rand() % 100;
    cout << "0-99 的随机数: " << range << endl;
    
    // 生成指定范围的随机数 (1-100)
    int range2 = rand() % 100 + 1;
    cout << "1-100 的随机数: " << range2 << endl;
    
    return 0;
}

六、其他常用数学函数

6.1 三角函数

cpp
double sin(double x);   // 正弦
double cos(double x);   // 余弦
double tan(double x);   // 正切

6.2 指数和对数函数

cpp
double exp(double x);   // e^x
double log(double x);   // 自然对数
double log10(double x); // 常用对数

6.3 幂函数

cpp
double pow(double base, double exponent);  // base^exponent

七、示例程序:计算三角形面积

7.1 海伦公式

cpp
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    double a, b, c;
    cout << "输入三角形三边: ";
    cin >> a >> b >> c;
    
    double s = (a + b + c) / 2;
    double area = sqrt(s * (s - a) * (s - b) * (s - c));
    
    cout << "三角形面积: " << area << endl;
    
    return 0;
}

7.2 生成随机数组

cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    srand(time(0));
    
    int arr[10];
    for (int i = 0; i < 10; i++) {
        arr[i] = rand() % 100;
    }
    
    cout << "随机数组: ";
    for (int num : arr) {
        cout << num << " ";
    }
    cout << endl;
    
    return 0;
}

百炼成钢,融会贯通