用c++6.0编写程序,自定义比较大小函数,输出两个数中的最大值。
时间: 2023-12-10 17:38:57 浏览: 81
以下是一个示例程序,使用自定义的比较大小函数 `myCompare()` 来输出两个数中的最大值:
```c++
#include <iostream>
using namespace std;
int myCompare(int a, int b) {
if (a > b) return a;
else return b;
}
int main() {
int num1, num2;
cout << "Please enter two numbers: ";
cin >> num1 >> num2;
cout << "The maximum number is: " << myCompare(num1, num2) << endl;
return 0;
}
```
在上面的代码中,`myCompare()` 函数接收两个整数参数 `a` 和 `b`,并通过比较它们的大小来返回更大的那一个数。在 `main()` 函数中,我们从用户输入两个整数,然后调用 `myCompare()` 函数并输出结果。
相关问题
c++使用自定义函数编程求两个数的最大值
可以使用自定义函数来编写C++程序,计算两个数的最大值,代码如下所示:
```c++
#include <iostream>
using namespace std;
int max(int a, int b) {
if(a > b) {
return a;
} else {
return b;
}
}
int main() {
int num1, num2;
cout << "请输入两个整数:";
cin >> num1 >> num2;
cout << num1 << "和" << num2 << "中的最大值为:" << max(num1, num2) << endl;
return 0;
}
```
这个程序中,我们定义了一个名为max的自定义函数,它接受两个整数作为参数,返回这两个数中的最大值。然后,在主函数中,我们使用cin语句从用户处输入两个整数,调用max函数来计算它们的最大值,并使用cout语句打印出结果。
用c++写出用子函数实现比较两个数的大小,在主函数中输出最大值
```c
#include <stdio.h>
int compare(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
int main() {
int num1, num2, max;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
max = compare(num1, num2);
printf("The maximum number is %d", max);
return 0;
}
```