输入数组int a[12]的元素,输出数组中重复次数最多的数。 输出格式:num: %d, times=%d
时间: 2023-12-03 22:42:50 浏览: 53
好的,下面是示例代码:
```c++
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
int a[12];
unordered_map<int, int> cnt; // 使用unordered_map来记录每个数的出现次数
for (int i = 0; i < 12; i++) {
cin >> a[i];
cnt[a[i]]++;
}
int max_num = -1, max_times = -1;
for (auto it : cnt) { // 遍历unordered_map
if (it.second > max_times) { // 找到出现次数最多的数
max_num = it.first;
max_times = it.second;
}
}
printf("num: %d, times=%d", max_num, max_times);
return 0;
}
```
输入示例:
```
1 2 3 3 3 4 4 4 4 5 6 6
```
输出示例:
```
num: 4, times=4
```
相关问题
c语言找到一个数组中出现次数最多的元素,并输出其出现次数
以下是一个找到数组中出现次数最多的元素和输出其出现次数的C语言代码示例:
```c
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7};
int n = sizeof(arr) / sizeof(int);
int max_count = 0;
int max_num = 0;
for (int i = 0; i < n; i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
if (count > max_count) {
max_count = count;
max_num = arr[i];
}
}
printf("The element that appears most frequently is %d, which appears %d times.\n", max_num, max_count);
return 0;
}
```
输出结果为:
```
The element that appears most frequently is 7, which appears 5 times.
```
该代码中,我们首先定义了一个整型数组`arr`,并计算出其元素个数`n`。然后,我们遍历数组中的所有元素,对于每个元素,我们又遍历一遍整个数组,统计出该元素在数组中出现的次数。如果该元素出现的次数比当前的最大值`max_count`要大,我们就更新`max_count`和`max_num`的值,分别记录出现次数最多的元素和其出现次数。最后,我们输出`max_num`和`max_count`的值即可。
Java输入数组找出出现次数最多的数
以下是一个示例程序,它接受用户输入的整数数组并找出出现次数最多的数字:
```
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int size = input.nextInt();
int[] arr = new int[size];
System.out.print("Enter the elements of the array: ");
for (int i = 0; i < size; i++) {
arr[i] = input.nextInt();
}
// Find the most frequently occurring number
int maxCount = 0;
int maxNum = arr[0];
for (int i = 0; i < size; i++) {
int count = 1;
for (int j = i+1; j < size; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
if (count > maxCount) {
maxCount = count;
maxNum = arr[i];
}
}
System.out.println("The most frequently occurring number is: " + maxNum);
System.out.println("It occurs " + maxCount + " times.");
}
}
```
该程序首先要求用户输入数组的大小和元素,然后使用嵌套循环来计算每个数字出现的次数。最后,它找到出现次数最多的数字并输出它以及它出现的次数。