使用C语言实现无重复数组:重复则重新输入10个整数
修复后的C语言去重输入程序
功能需求
- 提示用户输入10个整数
- 若输入的数组存在重复数字,提示用户重新输入
- 当输入的10个整数无重复时,结束程序
预期输出示例
Enter 10 elements in the array : Input 1: 1 Input 2: 2 Input 3: 3 Input 4: 4 Input 5: 5 Input 6: 5 Input 7: 5 Input 8: 6 Input 9: 7 Input 10: 8 5 is repeated, please enter numbers again Enter 10 elements in the array : Input 1: 1 Input 2: 2 Input 3: 3 Input 4: 4 Input 5: 5 Input 6: 6 Input 7: 7 Input 8: 8 Input 9: 9 Input 10: 0 There are no repeated numbers!
初始代码的问题分析
visited数组未初始化,每次循环前未重置为0,会导致判断逻辑混乱- 重复判断条件错误:
count >=1会将所有数字判定为重复(每个数字至少出现一次),正确条件应为count >1 do-while循环的终止条件错误,!array[i]逻辑不成立,无法正确控制循环- 输出逻辑错误:遍历过程中提前终止循环,未确认所有元素是否无重复就输出信息
修复后的代码
#include <stdio.h> int main() { int array[10]; int i, j, num = 10; int n = sizeof(array) / sizeof(array[0]); // 用于标记已检查过的元素,避免重复判断 int visited[10]; // 标记是否存在重复元素 int has_duplicate; do { has_duplicate = 0; // 初始化visited数组为0,确保每次循环都是全新状态 for (i = 0; i < n; i++) { visited[i] = 0; } printf("\nEnter %d elements in the array : \n", num); for (i = 0; i < n; i++) { printf("Input %d: ", i + 1); scanf("%d", &array[i]); } // 检查数组中是否存在重复元素 for (i = 0; i < n; i++) { if (visited[i] == 0) { int count = 1; for (j = i + 1; j < n; j++) { if (array[i] == array[j]) { count++; visited[j] = 1; } } // 出现次数大于1说明有重复 if (count > 1) { printf("%d is repeated, please enter numbers again \n", array[i]); has_duplicate = 1; break; } } } // 如果没有重复,输出成功信息 if (!has_duplicate) { printf("There are no repeated numbers!\n"); } // 存在重复则继续循环,重新输入 } while (has_duplicate); return 0; }
修复说明
- 增加
has_duplicate标志位,精准控制循环是否需要继续 - 每次循环开始时初始化
visited数组为0,避免历史数据干扰 - 修改重复判断条件为
count > 1,仅当元素出现多次时判定为重复 - 调整输出逻辑:遍历完所有元素确认无重复后,再输出成功提示
内容的提问来源于stack exchange,提问作者Eugeo
相关产品推荐
相关产品推荐

