4. 编程:分别以宏和函数形式求某个数的绝对值,并编程调用它们。内联(inline)函数虽然以函数形式定义,但在调用时相当于宏,将代码直接替换函数调用表达式,不需调用栈操作,可以节省栈空间和函数调用的时间开销;但要求函数代码简单,没有复杂语句。(选做)
时间: 2024-02-25 13:55:18 浏览: 51
宏定义求绝对值的代码如下:
```c++
#define ABS(x) ((x) > 0 ? (x) : -(x))
```
函数定义求绝对值的代码如下:
```c++
int abs(int x) {
return x > 0 ? x : -x;
}
```
内联函数定义求绝对值的代码如下:
```c++
inline int abs(int x) {
return x > 0 ? x : -x;
}
```
在主函数中调用它们的方法如下:
```c++
int main() {
int x = -5;
int y = ABS(x);
int z = abs(x);
int w = inline_abs(x);
cout << y << endl; // 输出 5
cout << z << endl; // 输出 5
cout << w << endl; // 输出 5
return 0;
}
```
相关问题
用内联函数实现求一个数的绝对值(不调用系统函数),并在main函数中调用。
以下是使用内联函数实现求一个数的绝对值的示例代码:
```c++
#include <iostream>
// 内联函数实现求一个数的绝对值
inline int abs(int x) {
return x >= 0 ? x : -x;
}
int main() {
int x = -10;
std::cout << "The absolute value of " << x << " is " << abs(x) << std::endl;
return 0;
}
```
在上面的代码中,我们使用 `inline` 关键字定义了一个内联函数 `abs`,它接受一个整数参数 `x`,并返回它的绝对值。在 `main` 函数中,我们调用了这个内联函数,并输出了结果。
内联函数的主要优点是可以减少函数调用的开销,因为内联函数的代码会直接插入到调用它的地方,从而避免了函数调用的开销。但是,内联函数也有一些缺点,比如会增加程序的代码量,因为每次调用内联函数时都会复制一遍函数的代码。因此,应该根据具体情况来决定是否使用内联函数。
利用内联函数编程求出自然数1-10中各个数的立方值
```c++
#include <iostream>
inline int cube(int x) { // 定义内联函数cube
return x * x * x;
}
int main() {
for (int i = 1; i <= 10; i++) {
std::cout << "The cube of " << i << " is " << cube(i) << std::endl;
}
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)