c++++ 内置函数可简化编程,其中常用的函数包括:cout: 打印输出到控制台cin: 从控制台读取输入abs: 返回绝对值sqrt: 计算平方根max/min: 返回最大值或最小值

C++ 内置函数的全面指南
C++ 提供了许多内置函数,它们可以帮助我们处理各种常见任务,从而简化编程。本文将介绍 C++ 中最常用的内置函数,并通过实际示例说明它们的用法。
1. cout
立即学习“C++免费学习笔记(深入)”;
用途:在控制台中打印输出。
语法:
示例:
|
1
2
3
4
5
6
|
#include <iOStream>
int main() {
cout << "Hello, world!" << endl;
return 0;
}
|
输出:
2. cin
用途:从控制台中读取输入。
语法:
示例:
|
1
2
3
4
5
6
7
8
9
|
#include <iostream>
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
cout << "You entered: " << number << endl;
return 0;
}
|
输出:
|
1
2
|
Enter a number: 10
You entered: 10
|
3. abs
用途:返回一个数字的绝对值。
语法:
示例:
|
1
2
3
4
5
6
7
8
|
#include <cstdlib>
int main() {
int number = -10;
int absolute_value = abs(number);
cout << "Absolute value of " << number << " is: " << absolute_value << endl;
return 0;
}
|
输出:
|
1
|
Absolute value of -10 is: 10
|
4. sqrt
用途:计算一个数字的平方根。
语法:
示例:
|
1
2
3
4
5
6
7
8
|
#include <cmath>
int main() {
double number = 16.0;
double square_root = sqrt(number);
cout << "Square root of " << number << " is: " << square_root << endl;
return 0;
}
|
输出:
|
1
|
Square root of 16.0 is: 4.0
|
5. max/min
用途:返回两个或多个数字中的最大值或最小值。
语法:
示例:
|
1
2
3
4
5
6
7
8
9
10
11
|
#include <algorithm>
int main() {
int a = 10;
int b = 5;
int max_value = max(a, b);
int min_value = min(a, b);
cout << "Max value is: " << max_value << endl;
cout << "Min value is: " << min_value << endl;
return 0;
}
|
输出:
|
1
2
|
Max value is: 10
Min value is: 5
|
更多内置函数
除了上述函数,C++ 还提供了许多其他有用的内置函数,包括: