C语言整数数组输入与指定数字搜索程序问题求助
C语言数组搜索程序的问题修正与优化
你的代码中的关键错误
scanf格式符错误:你把%d写成了&d,这会导致输入无法被正确读取,直接打乱程序流程。比如scanf("&d",&n);和scanf("&d",&a[i]);都是错误写法,必须改为%d。- 数组元素输出错误:
printf("%d",&a[i]);传递的是数组元素的内存地址,应该直接传递元素值a[i],否则输出的是地址而非数组内容。 - 搜索逻辑错误:当前代码在循环中每次判断都会输出结果,没找到目标时会重复打印“Element not found!”。正确逻辑是找到目标后标记位置并退出循环,循环结束后再统一判断是否未找到。
修正后的完整代码
#include <stdio.h> int main() { int a[10], n, i, key, found_pos = -1; // found_pos初始为-1表示未找到目标 printf("Enter how many numbers in an array: "); scanf("%d", &n); // 修正格式符为%d // 增加输入合法性校验,避免n超出数组容量 if(n < 1 || n > 10) { printf("Please enter a number between 1 and 10.\n"); return 1; } printf("Enter %d numbers in the array:\n", n); for(i = 0; i < n; i++) { scanf("%d", &a[i]); // 修正格式符 } printf("Display Array Elements:\n"); for(i = 0; i < n; i++) { printf("%d ", a[i]); // 输出元素值,增加空格分隔提升可读性 } printf("\n"); printf("Enter search value: "); scanf("%d", &key); // 优化搜索逻辑 for(i = 0; i < n; i++) { if(a[i] == key) { found_pos = i + 1; // 位置从1开始计数 break; // 找到目标后立即退出循环 } } // 统一输出结果 if(found_pos != -1) { printf("Number found at position %d\n", found_pos); } else { printf("Element not found!\n"); } return 0; }
其他实现方法
1. 动态分配数组(摆脱固定大小限制)
如果需要支持任意大小的数组,可以用malloc动态分配内存,灵活性更高:
#include <stdio.h> #include <stdlib.h> int main() { int *a, n, i, key, found_pos = -1; printf("Enter how many numbers in an array: "); scanf("%d", &n); if(n < 1) { printf("Please enter a positive number.\n"); return 1; } // 动态分配内存 a = (int*)malloc(n * sizeof(int)); if(a == NULL) { // 判断内存分配是否成功 printf("Memory allocation failed.\n"); return 1; } printf("Enter %d numbers in the array:\n", n); for(i = 0; i < n; i++) { scanf("%d", &a[i]); } printf("Display Array Elements:\n"); for(i = 0; i < n; i++) { printf("%d ", a[i]); } printf("\n"); printf("Enter search value: "); scanf("%d", &key); for(i = 0; i < n; i++) { if(a[i] == key) { found_pos = i + 1; break; } } if(found_pos != -1) { printf("Number found at position %d\n", found_pos); } else { printf("Element not found!\n"); } free(a); // 释放动态分配的内存 return 0; }
2. 函数化实现(代码结构更清晰)
把搜索逻辑封装成独立函数,便于复用和维护:
#include <stdio.h> // 搜索函数:返回目标位置(从1开始),未找到返回-1 int searchArray(int arr[], int size, int target) { for(int i = 0; i < size; i++) { if(arr[i] == target) { return i + 1; } } return -1; } int main() { int a[10], n, key, result; printf("Enter how many numbers in an array: "); scanf("%d", &n); if(n < 1 || n > 10) { printf("Please enter a number between 1 and 10.\n"); return 1; } printf("Enter %d numbers in the array:\n", n); for(int i = 0; i < n; i++) { scanf("%d", &a[i]); } printf("Display Array Elements:\n"); for(int i = 0; i < n; i++) { printf("%d ", a[i]); } printf("\n"); printf("Enter search value: "); scanf("%d", &key); result = searchArray(a, n, key); if(result != -1) { printf("Number found at position %d\n", result); } else { printf("Element not found!\n"); } return 0; }
内容的提问来源于stack exchange,提问作者Accelerator
相关产品推荐
相关产品推荐

