Board logo

標題: [技術討論] C program for loop同array問題 [打印本頁]

作者: kratos    時間: 2020-1-23 21:20     標題: 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;
}
作者: sonichkhk    時間: 2020-1-23 23:01

回覆 1# kratos

因為當num[j] 大過0 後 MAX就會變成num[j], 而之後再比較時MAX已不再是0了,經過5次 MAX自然是5個數中最大
作者: BudaHK    時間: 2020-1-23 23:08

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



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

有無試過輸入5個負數?
作者: CVSDF    時間: 2020-1-24 19:34

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)
作者: java2    時間: 2020-1-25 01:03

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

作者: testest    時間: 2020-1-25 02:27

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

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



    Haha 有bug
作者: ckmakit    時間: 2020-1-25 16:22

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

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


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





歡迎光臨 電腦領域 HKEPC Hardware (https://h0.hkepc.com/forum/) Powered by Discuz! 7.2