[技術討論] C program for loop同array問題

寫一個program要user入5個數
最後output要出到邊個數最大同埋係第幾個數最大,下面就係答案,但係有小小野唔明


#include <stdlib.h>
#include <stdio.h>

int main (){
       
       
int i, j, num[5], max=0, pos=0;
printf("Input 5 integer: \n");

for(i=0; i<5; i++)
{
scanf(" %d", &num[i]);
}

for(j=0; j<5; j++)
{
if(num[j]>max)
{
max = num[j];
pos = j;
}
}
printf("Highest value: %d\n", max);
printf("Position: %d", pos+1);
       
        system("pause");
        return 0;
}


呢個program最後可以完全成功做到哂要求但唔太明點解呢段code,點解max set左做0,但又會用num[j]去同max比較之後又會出得番最大的數?有冇高手可以解到?thank you
if(num[j]>max)
{
max = num[j];
pos = j;
}

回覆 1# kratos

因為當num[j] 大過0 後 MAX就會變成num[j], 而之後再比較時MAX已不再是0了,經過5次 MAX自然是5個數中最大

TOP

寫一個program要user入5個數
最後output要出到邊個數最大同埋係第幾個數最大,下面就係答案,但係有小小野唔 ...
kratos 發表於 2020-1-23 21:20



    "呢個program最後可以完全成功做到哂要求"

有無試過輸入5個負數?

TOP

1. [max] is for storing the final answer, and is init to 0
2. num[j] is the current item in the loop
3. [max] now pk with each one in the loop (num[j]), if num[j] wins, [max] store that as champion, and [pos] store where the champion came from (array position)

TOP

max set 做0 咪由0 開始比較最大.

但比我寫會
for(pos=0,max=num[0], j=1; j<5; j++)
{
if(num[j]>max)
{
max = num[j];
pos = j;
}
}

寫一個program要user入5個數
最後output要出到邊個數最大同埋係第幾個數最大,下面就係答案,但係有小小野唔 ...
kratos 發表於 2020-1-23 21:20

TOP

"呢個program最後可以完全成功做到哂要求"

有無試過輸入5個負數?
BudaHK 發表於 2020-1-23 23:08



    Haha 有bug

TOP

"呢個program最後可以完全成功做到哂要求"

有無試過輸入5個負數?
BudaHK 發表於 2020-1-23 23:08


仲有0
...咁如果5個數字都一樣呢

TOP