为何C语言求最大值程序输入8,10,25,75,100时结果为100而非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 = 0andnum_pos = 0 - You read 5 integers into the
numberarray:[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] = 8is greater than the initialmax=0, so we updatemax=8andnum_pos=0. This is the part you noticed. - j=1:
number[1] = 10is greater than the currentmax=8, so we updatemax=10andnum_pos=1. - j=2:
number[2] = 25is greater thanmax=10, somax=25andnum_pos=2. - j=3:
number[3] = 75is greater thanmax=25, somax=75andnum_pos=3. - j=4:
number[4] = 100is greater thanmax=75, somax=100andnum_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

