You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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;
}

代码问题分析

  1. 数组访问错误:C语言数组的正确访问格式是数组名[索引],你写的ship[array]完全颠倒,正确写法应为array[ship]。
  2. 类型与格式符不匹配:array是int类型数组,却用%li(long int格式符)读取和打印,应该用%d;另外索引变量用int类型足够,无需long int。
  3. 变量复用逻辑混乱:用ship同时充当循环索引、输入存储变量,输入0后还重置ship为0,直接破坏了原循环的计数逻辑。
  4. 无限循环风险:输入0后进入的while(ship[array] == 0)没有退出条件,会持续重复打印内容。
  5. 缺少合法性检查:未判断输入是否在[1,100]区间内,无法识别非法输入。
  6. 循环语法错误:最后一个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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:31:02