请大家帮忙解决一个问题
这个题目是《C语言解析教程》里面第九章后面的习题因为我是自学,这个题目不会解,请大家帮忙解答。
题目如下:
编写一个程序,把 n 个数读入一个数组,然后分行显示不同元素的值及其出现的次数。例如:
输入: -7 3 3 -7 5 5 3
那么程序应该显示:
5 occurs 2 times
3 occurs 3 times
-7 occurs 2 times
我目前还只学到数组,所以程序不要太深了,不然看不懂。谢谢。
#include<stdio.h> #include "stdlib.h" void main() { //1.input array's size: int n; printf("input array size n:\n"); scanf("%d",&n); int *array = (int*) malloc(n); //2.input array: printf("input array:\n"); int i; for(i=0;i<n;i++) scanf("%d",&array[i]); //3.sort array: int temp; for(i=0;i<n;i++) { for(int j=i;j<n;j++) { if(array[i]>array[j]) { temp = array[i]; array[i] = array[j]; array[j] = temp; } } } //4.ouput the occur times: int count = 1; for(i=1;i<n;i++) { if(array[i-1] == array[i]) { count++; if(i == n-1) printf(" %d occurs %d times\n",array[i],count); continue; } else { printf(" %d occurs %d times\n",array[i-1],count); count = 1; } } free(array); return; }
#include<stdio.h> #include <stdlib.h> void main() { printf("input array's size n:\n"); int n; scanf("%d",&n); if(n<=0) { printf("invalid n: %d\n",n); return; } printf("input the array:\n"); //int *array = (int *)malloc(n); int *array = new int[n]; for(int i=0;i<n;i++) { scanf("%d",&array[i]); } int count=1; int target; bool isCount = false; for(i=0;i<n;i++) { target = array[i]; for(int j=0;j<i;j++) { if(target == array[j]) { isCount = true; break; } else { continue; } } //isCount is false; it means target(array[i]) is not contained in the previous elememts:array[0]~array[i-1] if(false == isCount) { for(int k=i;k<n;k++) { if(target == array[k] && i != k) { count++; } if(n-1 == k) { printf(" %d occurs %d times\n",target,count); isCount = false; count = 1; } } } else { isCount = false; continue; } } //free(array); delete [] array; return; }