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

为何C语言求最大值程序输入8,10,25,75,100时结果为100而非8?

Why does the max end up as 100 even though it first becomes 8?

Hey there! Let's walk through exactly how your code works to clear up that confusion.

First, let's recap the key parts of your code:

  • You initialize max = 0 and num_pos = 0
  • You read 5 integers into the number array: [8, 10, 25, 75, 100]
  • Then you loop through each element in the array to find the maximum value

Step-by-step breakdown of the second loop:

Let's track the value of max and num_pos through each iteration of the loop (where j goes from 0 to 4):

  • j=0: number[0] = 8 is greater than the initial max=0, so we update max=8 and num_pos=0. This is the part you noticed.
  • j=1: number[1] = 10 is greater than the current max=8, so we update max=10 and num_pos=1.
  • j=2: number[2] = 25 is greater than max=10, so max=25 and num_pos=2.
  • j=3: number[3] = 75 is greater than max=25, so max=75 and num_pos=3.
  • j=4: number[4] = 100 is greater than max=75, so max=100 and num_pos=4.

By the end of the loop, max gets updated every time we hit a number larger than the current maximum. That's why it doesn't stay at 8—it keeps getting replaced by bigger values as we check the rest of the array.

A quick optimization note:

Right now, initializing max=0 works fine for positive numbers, but if all input numbers were negative (e.g., -5, -3, -10), the code would incorrectly return 0 as the maximum. To fix this, initialize max to the first element of the array instead:

int max = number[0];
int num_pos = 0;

This way, you start comparing against actual input values right from the start.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:00:45