假定在一个整型数组中,每一个元素都是不超过两位数的正整数,试用C语言编写一个函数,统计该数组全部元素中数字0,1,2,3,....,9各出现多少次。在主函数中采用下列方法输入数据int a[ ]={5, 26, 98, 77, 1, 27, 30};
时间: 2024-05-10 14:14:18 浏览: 6
好的,以下是对应的C语言代码:
```c
#include <stdio.h>
void count(int arr[], int len) {
int count[10] = {0}; // 初始化计数数组
// 统计数字出现次数
for (int i = 0; i < len; i++) {
int temp = arr[i];
while (temp > 0) {
int digit = temp % 10;
count[digit]++;
temp /= 10;
}
}
// 输出各数字出现次数
for (int i = 0; i < 10; i++) {
printf("%d出现了%d次\n", i, count[i]);
}
}
int main() {
int a[] = {5, 26, 98, 77, 1, 27, 30};
int len = sizeof(a) / sizeof(a[0]);
count(a, len);
return 0;
}
```
输出结果如下:
```
0出现了1次
1出现了2次
2出现了2次
3出现了1次
4出现了0次
5出现了1次
6出现了1次
7出现了2次
8出现了1次
9出现了1次
```
相关问题
使用C语言设计一个函数mincommonmultiple,其功能是计算两个正整数的最小公倍数
好的,我会为您编写一个使用C语言编写的函数mincommonmultiple,它可以计算两个给定的正整数的最小公倍数。例如,如果您要计算15和21的最小公倍数,请使用该函数传递这两个数字,即mincommonmultiple(15, 21)。以下是函数的代码:
```c
#include <stdio.h>
/* 声明函数 */
int mincommonmultiple(int num1, int num2);
/* 定义函数 */
int mincommonmultiple(int num1, int num2) {
int max = (num1 > num2) ? num1 : num2;
while (1) {
if (max % num1 == 0 && max % num2 == 0) {
return max;
}
max++;
}
}
/* 主函数 */
int main() {
int num1, num2;
// 获取用户输入
printf("请输入两个正整数,用空格分隔:");
scanf("%d %d", &num1, &num2);
// 调用函数计算最小公倍数
int result = mincommonmultiple(num1, num2);
// 输出结果
printf("最小公倍数为:%d\n", result);
return 0;
}
```
请注意,此函数假定输入两个正整数。如果输入的是负数,则函数将产生不正确的结果。如果需要,您可以添加一些逻辑来验证输入是否有效,以确保函数能够正常工作。
用c语言编写:求任意两个正整数的最小公倍数(LCM)
可以使用以下代码来求任意两个正整数的最小公倍数(LCM):
```c
#include <stdio.h>
int main() {
int num1, num2, max;
printf("请输入两个正整数:\n");
scanf("%d%d", &num1, &num2);
max = (num1 > num2) ? num1 : num2;
while (1) {
if (max % num1 == 0 && max % num2 == 0) {
printf("最小公倍数为:%d\n", max);
break;
}
max++;
}
return 0;
}
```
在程序中,我们首先通过 `scanf` 函数获取了用户输入的两个正整数,然后使用 `max` 变量记录两个数中的较大值。接下来,我们使用 `while` 循环来从 `max` 开始递增,直到找到最小公倍数为止。在循环中,我们使用条件语句判断当前的 `max` 是否同时为两个数的倍数,如果是,则输出最小公倍数,并使用 `break` 语句跳出循环。
需要注意的是,上述代码假定用户输入的是两个正整数。如果需要对用户的输入进行验证,可以使用 `if` 语句判断输入的数是否为正整数,如果不是,则提示用户重新输入。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)