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

C语言不用列表仅用for循环与if语句实现10个整数分类计数及最值求解

问题排查与修正方案

现存代码的核心问题

  • 最大/最小值判断逻辑完全错误:当前判断条件为postiveNum >= postiveNum这类恒成立的表达式,赋值对象也误用了正数计数变量,和实际输入的数值完全无关,自然无法得到正确的最大最小值。
  • 最大/最小值初始化逻辑错误:初始值固定为0,若输入全为负数则最大值会错误显示为0,若输入全为正数则最小值会错误显示为0。
  • 提示语逻辑不符:原代码只提示输入1次,实际需要输入10个整数。

修正后代码

#include <stdio.h>
int main()
{
    int numInput;
    int count;
    int postiveNum = 0, negativeNum = 0, oddNum = 0, evenNum = 0, largestNum, smallestNum;
    printf("Please input 10 integers: \n");
    for(count = 1; count <= 10; count++)
    {
        scanf("%d", &numInput);
        // 第一个输入值直接作为最大最小的初始值
        if(count == 1) {
            largestNum = numInput;
            smallestNum = numInput;
        } else {
            // 和当前输入值比较更新最大最小
            if(numInput > largestNum) {
                largestNum = numInput;
            }
            if(numInput < smallestNum) {
                smallestNum = numInput;
            }
        }
        // 统计正负
        if(numInput > 0) {
            postiveNum++;
        } else if(numInput < 0) {
            negativeNum++;
        }
        // 统计奇偶,兼容负数取模逻辑
        if(numInput % 2 != 0) {
            oddNum++;
        } else {
            evenNum++;
        }
    }
    printf("Positive Numbers: %d\n", postiveNum);
    printf("Negative Numbers: %d\n", negativeNum);
    printf("Odd Numbers: %d\n", oddNum);
    printf("Even Numbers: %d\n", evenNum);
    printf("Largest Number: %d\n", largestNum);
    printf("Smallest Number: %d\n", smallestNum);
    return 0;
}

修正说明

  • 新增了第一个输入值初始化最大最小值的逻辑,避免初始固定值带来的统计偏差
  • 把最大最小值的判断改为和当前输入的numInput比较,逻辑完全符合需求
  • 优化了分支判断,减少不必要的if判断次数
  • 补充了main函数的返回值,符合C语言语法规范

内容的提问来源于stack exchange,提问作者calister28

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:15:06