用c++编写一个函数,输出3个数中最大数
时间: 2024-02-19 14:02:51 浏览: 29
以下是用C++编写的函数,可输出3个数中的最大数:
```cpp
#include <iostream>
using namespace std;
int max(int a, int b, int c){
int max = a;
if (b > max) {
max = b;
}
if (c > max) {
max = c;
}
return max;
}
int main(){
int a, b, c;
cout << "请输入三个整数:" << endl;
cin >> a >> b >> c;
cout << "最大数为:" << max(a, b, c) << endl;
return 0;
}
```
在上面的代码中,我们使用了一个 `max` 函数,该函数接收3个整数作为参数,并返回它们中的最大值。在 `main` 函数中,我们从控制台输入3个整数,并将它们传递给 `max` 函数,然后输出结果。
相关问题
c++编写一个函数可以求出整数的位数
您可以使用以下代码来编写一个函数,以计算一个整数的位数:
```cpp
#include <iostream>
int countDigits(int num) {
int count = 0;
if (num == 0) {
return 1; // 对于0,位数为1
} else {
while (num != 0) {
num /= 10;
count++;
}
return count;
}
}
int main() {
int num;
std::cout << "请输入一个整数:";
std::cin >> num;
int digits = countDigits(num);
std::cout << "该整数的位数为:" << digits << std::endl;
return 0;
}
```
在上述代码中,我们定义了一个名为`countDigits()`的函数,它接受一个整数作为参数,然后使用循环和除法操作来计算该整数的位数。首先,如果输入的整数是0,则直接返回1(0的位数为1)。否则,我们使用一个循环来反复将整数除以10,并且每次除法操作后将计数器加1,直到整数变为0。最后,返回计数器的值作为位数。
在`main()`主函数中,我们首先输入一个整数,并将其传递给`countDigits()`函数进行位数计算。然后,我们将计算得到的位数打印输出。
编译并运行该代码,您可以输入一个整数,然后看到该整数的位数被打印输出。
用c++编写一个子函数实现月份全部输出
以下是用C++编写的子函数实现月份全部输出的示例代码:
```cpp
#include <iostream>
using namespace std;
void printMonths() {
string months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
for(int i = 0; i < 12; i++) {
cout << months[i] << endl;
}
}
int main() {
printMonths();
return 0;
}
```
该程序中,定义了一个字符串数组 `months`,其中存储了所有的月份。接着,在 `printMonths()` 函数中,使用 `for` 循环遍历数组,逐个输出每个月份。最后,在 `main()` 函数中调用 `printMonths()` 函数即可实现月份全部输出。
相关推荐
![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)