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

C语言作业问题:输入5个数后最小值输出0而非实际值

Troubleshooting: C Program Outputs 0 as Minimum Value

Hey there! Let's figure out why your minim variable is stuck outputting 0 instead of the actual smallest number you input. This is a super common pitfall when calculating min/max values in C, so let's walk through the most likely fixes:

Common Causes & Fixes

1. Incorrect Initialization of minim

The most frequent issue here is initializing minim to 0. If all the numbers you input are positive, 0 will always be smaller than them—so your program never updates minim to a new value.

Fix: Instead of setting minim = 0, initialize it with the first number you read from the user. That way, you're starting with a value that's actually part of your input set.

2. Backwards Comparison Logic

Double-check your if statement for updating minim. If you wrote something like:

if (minim < num) { // This is wrong!
    minim = num;
}

You're updating minim only when it's smaller than the current number—which means it'll never get set to a smaller value. The correct logic is:

if (num < minim) { // Check if current number is smaller than the current min
    minim = num;
}

3. Variable Scope Issues

Make sure minim is declared outside your loop. If you define it inside the loop, it gets reinitialized every iteration, and the final value you output will still be the initial 0.

Working Example Code

Here's a complete, corrected version of your program to reference:

#include <stdio.h>

int main() {
    int num, minim, maxim, sum = 0;
    float average;

    // Read first number and initialize min/max with it
    printf("Enter number 1: ");
    scanf("%d", &num);
    minim = num;
    maxim = num;
    sum += num;

    // Process remaining 4 numbers
    for (int i = 2; i <= 5; i++) {
        printf("Enter number %d: ", i);
        scanf("%d", &num);
        sum += num;

        // Update minimum if current number is smaller
        if (num < minim) {
            minim = num;
        }

        // Update maximum if current number is larger
        if (num > maxim) {
            maxim = num;
        }
    }

    average = (float)sum / 5; // Cast sum to float for accurate division

    // Print results
    printf("\nMinimum value: %d\n", minim);
    printf("Maximum value: %d\n", maxim);
    printf("Sum of numbers: %d\n", sum);
    printf("Average of numbers: %.2f\n", average);

    return 0;
}

Go ahead and check your code against these points—chances are the fix is in the initialization or comparison step. Let me know if you still run into issues after trying these!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:53:12