创建一个函数比较两个数大小
时间: 2024-06-23 22:02:56 浏览: 125
创建一个简单的函数来比较两个数的大小,通常在许多编程语言中都可以实现,比如Python、C++或JavaScript。这里我用Python和C++为例来展示如何编写这样的函数:
**Python:**
```python
def compare_numbers(a, b):
if a > b:
return "a is greater than b"
elif a < b:
return "a is less than b"
else:
return "a is equal to b"
# 示例用法
result = compare_numbers(10, 5)
print(result) # 输出:a is greater than b
```
**C++:**
```cpp
#include <iostream>
#include <string>
std::string compare_numbers(int a, int b) {
if (a > b) {
return "a is greater than b";
} else if (a < b) {
return "a is less than b";
} else {
return "a is equal to b";
}
}
int main() {
int num1 = 10;
int num2 = 5;
std::cout << compare_numbers(num1, num2) << std::endl; // 输出:a is greater than b
return 0;
}
```
在上述代码中,`compare_numbers`函数接受两个参数,比较它们的值,并返回一个字符串描述它们之间的关系。
阅读全文