73 lines
1.9 KiB
C
73 lines
1.9 KiB
C
/*----------------------------------------------------------------------
|
|
【程序设计】
|
|
------------------------------------------------------------------------
|
|
编写一个 C 语言函数,函数接收一个整数数组 arr 以及数组的长度 size 作为参
|
|
数,使用 bool 类型返回该数组中是否存在重复的元素。在 main 函数中,输入多
|
|
个正整数(输入非数字字符表示输入结束)并调用该函数,根据返回结果输出相应
|
|
的提示信息。
|
|
示例:
|
|
【请输入多个整数(输入非数字字符结束输入):】1 2 3 4 5 5 6 a
|
|
数组中存在重复元素。
|
|
------------------------------------------------------------------------
|
|
注意:部分源程序给出如下。请勿改动主函数 main 或其它函数中给出的内容,仅
|
|
在
|
|
Program-End 之间填入若干语句。
|
|
不要删除标志否则不得分。
|
|
不要修改或删除Program-End 之外的内容否则不得分。
|
|
----------------------------------------------------------------------*/
|
|
#include <stdio.h>
|
|
#include <stdbool.h>
|
|
#include <stdlib.h>
|
|
bool hasDuplicates(int arr[], int size)
|
|
{
|
|
/**********Program**********/
|
|
int i,j;
|
|
for(i=0;i<size-1;i++){
|
|
for(j=i+1;j<size;j++){
|
|
if(arr[i]==arr[j]){
|
|
return 1;
|
|
}
|
|
}
|
|
}
|
|
return 0;
|
|
/********** End **********/
|
|
}
|
|
int main()
|
|
{
|
|
int capacity = 10;
|
|
int *arr = (int *)malloc(capacity * sizeof(int));
|
|
if (arr == NULL)
|
|
{
|
|
printf("内存分配失败!\n");
|
|
return 1;
|
|
}
|
|
int size = 0;
|
|
int num;
|
|
printf("【请输入多个整数(输入非数字字符结束输入):】");
|
|
while (scanf("%d", &num) == 1)
|
|
{
|
|
if (size == capacity)
|
|
{
|
|
capacity *= 2;
|
|
arr = (int *)realloc(arr, capacity * sizeof(int));
|
|
if (arr == NULL)
|
|
{
|
|
printf("内存分配失败!\n");
|
|
return 1;
|
|
}
|
|
}
|
|
arr[size++] = num;
|
|
}
|
|
while (getchar() != '\n');
|
|
if (hasDuplicates(arr, size))
|
|
{
|
|
printf("数组中存在重复元素。\n");
|
|
}
|
|
else
|
|
{
|
|
printf("数组中不存在重复元素。\n");
|
|
}
|
|
free(arr);
|
|
return 0;
|
|
}
|