用函数编程,从键盘随机输入4个数,输出最大的数。
时间: 2024-03-15 10:46:07 浏览: 30
好的,以下是C语言代码实现:
```c
#include <stdio.h>
int max(int a, int b) { // 比较两个数的大小,返回较大的那个数
return a > b ? a : b;
}
int main() {
int a, b, c, d;
printf("请输入四个整数:\n");
scanf("%d %d %d %d", &a, &b, &c, &d);
int max1 = max(a, b); // 比较a和b的大小,得到较大的那个数
int max2 = max(c, d); // 比较c和d的大小,得到较大的那个数
int result = max(max1, max2); // 比较max1和max2的大小,得到最大的数
printf("最大的数为:%d\n", result);
return 0;
}
```
运行结果:
```
请输入四个整数:
12 34 56 78
最大的数为:78
```
这样就可以从键盘随机输入4个数,输出最大的数了。
相关问题
c语言编程实现产生随机的6位数字验证码并从键盘验证
下面是一个c语言实现产生随机的6位数字验证码并从键盘验证的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int code, guess, count = 0;
srand((unsigned)time(NULL)); // 设置随机数种子
// 生成验证码
code = rand() % 900000 + 100000;
printf("验证码已生成,请输入验证码(6位数字):\n");
// 验证验证码
while (count < 10) // 最多猜测10次
{
scanf("%d", &guess);
count++;
if (guess == code)
{
printf("验证成功!\n");
break;
}
else
{
printf("验证失败,请重新输入(还可以尝试%d次):\n", 10 - count);
}
}
if (count == 10)
{
printf("验证失败,您已经尝试了10次。\n");
}
return 0;
}
```
这个程序首先使用 `srand()` 函数设置随机数种子,然后使用 `rand()` 函数生成一个 6 位数字验证码。程序要求用户从键盘输入验证码,并在最多猜测10次后判断是否正确。如果猜测正确,则输出“验证成功”,否则输出“验证失败”并提示还有几次机会。在10次猜测机会用完后,程序输出“验证失败,您已经尝试了10次”。
编程实现从键盘随机的输入一串字符(不超过100个),统计出其中英文字母、数字和其它字符的个数并输出。
好的,以下是 C++ 代码实现:
```cpp
#include <iostream>
using namespace std;
int main() {
const int MAX_LEN = 100;
char str[MAX_LEN + 1];
cin.getline(str, MAX_LEN + 1);
int num_alpha = 0, num_digit = 0, num_other = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
num_alpha++;
} else if (isdigit(str[i])) {
num_digit++;
} else {
num_other++;
}
}
cout << "Alphabets: " << num_alpha << endl;
cout << "Digits: " << num_digit << endl;
cout << "Others: " << num_other << endl;
return 0;
}
```
代码中首先定义了一个常量 `MAX_LEN` 表示输入字符串的最大长度,然后定义了一个字符数组 `str`,使用 `cin.getline()` 从键盘读入字符串。接下来使用循环遍历字符串,对于每个字符判断其是否是字母、数字或其它字符,并统计个数。最后输出结果。其中用到了 C++ 标准库中的 `isalpha()` 和 `isdigit()` 函数,分别用于判断字符是否是字母和数字。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![png](https://img-home.csdnimg.cn/images/20210720083516.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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)