用指向变量的指针变量做函数参数,编写函数求两个数的关系
时间: 2024-05-04 16:20:56 浏览: 18
函数原型可以定义为:
```c
void compare(int *a, int *b);
```
其中,`int *a` 和 `int *b` 分别是指向整型变量的指针变量,表示要比较的两个数。
函数实现如下:
```c
void compare(int *a, int *b) {
if (*a > *b) {
printf("%d 大于 %d\n", *a, *b);
} else if (*a < *b) {
printf("%d 小于 %d\n", *a, *b);
} else {
printf("%d 等于 %d\n", *a, *b);
}
}
```
在函数体内,使用 `*a` 和 `*b` 分别获取指针变量所指向的实际变量的值,然后进行比较,并输出结果。
使用示例:
```c
int main() {
int x = 3, y = 5;
compare(&x, &y);
return 0;
}
```
输出结果为:
```
3 小于 5
```
相关问题
使用指向变量的指针变量做函数参数,编写函数求两个数的大于 小于 等于关系
好的,让我来回答你的问题。你可以通过以下代码使用指向变量的指针变量做函数参数,编写函数求两个数的大于、小于、等于关系:
```c++
#include <iostream>
using namespace std;
void compare(int num1, int num2, int *greater, int *less, int *equal) {
if (num1 > num2) {
*greater = num1;
*less = num2;
*equal = 0;
} else if (num1 < num2) {
*greater = num2;
*less = num1;
*equal = 0;
} else {
*greater = 0;
*less = 0;
*equal = num1;
}
}
int main() {
int num1 = 5, num2 = 3;
int greater, less, equal;
compare(num1, num2, &greater, &less, &equal);
if (greater != 0) {
cout << num1 << " is greater than " << num2 << endl;
}
if (less != 0) {
cout << num1 << " is less than " << num2 << endl;
}
if (equal != 0) {
cout << num1 << " is equal to " << num2 << endl;
}
return 0;
}
```
在这个代码中,compare()函数使用指向变量的指针变量来存储大于、小于和等于的结果。在调用函数时,使用&号取出变量的地址,并将它们作为参数传递给函数。函数中,可以通过解引用指针变量并直接在变量上操作来修改变量的值。最后,在主函数中,我们检查大于、小于和等于变量是否被修改,如果是,则输出相应的消息。
使用指向变量的指针变量做函数参数,编写函数求两个数的平方立方
可以先声明一个函数,函数的参数是两个指向整型变量的指针变量,函数的返回值类型为 void,具体实现如下:
```c
#include <stdio.h>
void squareAndCube(int *p1, int *p2) {
*p1 = (*p1) * (*p1);
*p2 = (*p2) * (*p2) * (*p2);
}
int main() {
int a = 2, b = 3;
printf("a = %d, b = %d\n", a, b);
squareAndCube(&a, &b);
printf("a^2 = %d, b^3 = %d\n", a, b);
return 0;
}
```
在这个例子中,我们先声明了一个 `squareAndCube` 函数,它有两个指向整型变量的指针变量 `p1` 和 `p2` 作为参数。函数的实现很简单,就是将 `p1` 指向的变量平方,将 `p2` 指向的变量立方。在 `main` 函数中,我们声明了两个整型变量 `a` 和 `b`,然后调用 `squareAndCube` 函数,并将 `a` 和 `b` 的地址作为参数传递给了 `squareAndCube` 函数。最后输出 `a` 和 `b` 的平方和立方。
相关推荐
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)