C语言基础入门求助:实现100个有效数字输入与输出程序
C语言程序问题求助与代码反馈
需求说明
- 从键盘读取最多100个输入,输入必须是[1,100]之间的数字
- 输入"0"时,程序退出循环并显示所有非0输入组成的数组
我正在学习C语言基础,尝试用while、for、if语句实现,但逻辑理解有困难,目前写出了如下代码,希望能得到指导、建议和反馈。我是第一次编程,若有不足请见谅。
#include <stdio.h> int main(){ int long ship; int array[100]; for(ship = 0; ship < 100; ship++){ printf("Repaired ship: "); scanf("%li", &ship[array]); while(ship[array] == 0){ printf("\n\t"); for(ship = 0; ship < 100; ship++) printf("%li ", ship[array]); printf("\n\nRepaired ships: %li", ship); } } if(ship == 100){ printf("\n\t"); for(ship = 0; ship < 100; ship) printf("%li ", ship[array]); printf("\n\nRepaired ships: %li", ship); } return 0; }
代码问题分析
- 数组访问错误:C语言数组的正确访问格式是
数组名[索引],你写的ship[array]完全颠倒,正确写法应为array[ship]。 - 类型与格式符不匹配:
array是int类型数组,却用%li(long int格式符)读取和打印,应该用%d;另外索引变量用int类型足够,无需long int。 - 变量复用逻辑混乱:用
ship同时充当循环索引、输入存储变量,输入0后还重置ship为0,直接破坏了原循环的计数逻辑。 - 无限循环风险:输入0后进入的
while(ship[array] == 0)没有退出条件,会持续重复打印内容。 - 缺少合法性检查:未判断输入是否在[1,100]区间内,无法识别非法输入。
- 循环语法错误:最后一个for循环
for(ship = 0; ship < 100; ship)缺少自增操作ship++,会导致死循环。
修改后的代码示例
#include <stdio.h> int main() { int array[100]; int count = 0; // 记录有效输入的个数 int input; while (count < 100) { printf("请输入1-100之间的数字(输入0结束):"); scanf("%d", &input); // 输入0时直接退出循环 if (input == 0) { break; } // 检查输入是否在合法区间 if (input >= 1 && input <= 100) { array[count] = input; count++; } else { printf("输入不合法,请输入1-100之间的数字!\n"); } } // 打印结果 printf("\n已输入的有效数字:"); for (int i = 0; i < count; i++) { printf("%d ", array[i]); } printf("\n有效数字总数:%d\n", count); return 0; }
代码说明
- 用
count单独记录有效输入数量,避免索引和计数变量混淆。 - 用
while循环控制输入流程,直到输入0或达到100个有效输入。 - 增加输入合法性检查,非法输入会提示用户重新输入。
- 打印结果时仅遍历已输入的有效元素,不会输出数组中未初始化的垃圾值。
内容的提问来源于stack exchange,提问作者Basick
相关产品推荐
相关产品推荐

