C语言用函数比较两个数大小
时间: 2023-12-12 17:35:56 浏览: 140
以下是C语言比较两个数大小的函数示例:
```c
#include <stdio.h>
int compare(int a, int b) {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
} else {
return 0;
}
}
int main() {
int a = 10;
int b = 20;
int result = compare(a, b);
if (result == 1) {
printf("%d is greater than %d\n", a, b);
} else if (result == -1) {
printf("%d is less than %d\n", a, b);
} else {
printf("%d is equal to %d\n", a, b);
}
return 0;
}
```
该函数接受两个整数作为参数,返回值为1表示第一个参数大于第二个参数,返回值为-1表示第一个参数小于第二个参数,返回值为0表示两个参数相等。在主函数中,我们调用compare函数比较a和b的大小,并根据返回值打印出相应的结果。
相关问题
C语言调用函数比较两个数的大小
以下是C语言调用函数比较两个数大小的例子:
引用:
```c
#include <stdio.h>
int Max(int a, int b); // 函数声明
int main() {
int a = 0;
int b = 0;
printf("Please enter two numbers:");
scanf("%d %d", &a, &b);
printf("The max is %d\n", Max(a, b)); // 调用函数
}
int Max(int a, int b) {
if (a < b) {
return b;
} else {
return a;
}
}
```
引用:
```c
int Max(int a, int b) {
if (a < b) {
return b;
} else {
return a;
}
}
```
以上代码中,我们定义了一个名为Max的函数,该函数接受两个整数参数a和b,并返回它们中的最大值。在主函数中,我们通过scanf函数从用户输入中获取两个整数,然后调用Max函数来比较它们的大小并输出结果。
用c语言比较两个数的大小
以下是用C语言比较两个数大小的代码示例:
```c
#include <stdio.h>
int main() {
int num1, num2;
printf("请输入两个整数,用空格隔开:");
scanf("%d %d", &num1, &num2);
if (num1 > num2) {
printf("%d 比 %d 大\n", num1, num2);
} else if (num1 < num2) {
printf("%d 比 %d 小\n", num1, num2);
} else {
printf("%d 等于 %d\n", num1, num2);
}
return 0;
}
```
在这个示例中,我们使用了`if-else`语句来比较两个整数的大小。首先,我们使用`scanf`函数获取用户输入的两个整数。然后,我们使用`if-else`语句来比较这两个整数的值,如果第一个整数比第二个整数大,则输出第一个整数比第二个整数大;如果第一个整数比第二个整数小,则输出第一个整数比第二个整数小;否则,它们相等,我们输出它们相等。