2016-05-20 4 views
1

私は5つの入力倍精度の中で最小値を見つけるための機能に取り組んでいます。私はオンラインで参考文献を見つけました。エラー:スレッド1:EXC_BAD_ACCESS(コード= 1、アドレス= 0x7fff5fc89000)最低値を見つける。関数。エラー:スレッド1:EXC_BAD_ACCESS(コード= 1、アドレス= 0x7fff5fc89000)

私のコードはどこですか?感謝します!

オンラインリファレンス:

int findLowest(int s1, int s2, int s3, int s4, int s5) 
{ 
         int lowest = s1; 
          
          
    if (s2 < lowest)        
         { 
                  lowest = s2; 
         } 
         else if (s3 < lowest) 
         { 
                  lowest = s3; 
         } 
         else if (s4 < lowest) 
    { 
                  lowest = s4; 
         } 
         else if (s5 < lowest) 
         { 
                  lowest = s5; 
         } 
   
         cout << "The lowest test score is: " << lowest << endl; 
   
    return lowest; 
} 

出典:配列とhttp://cboard.cprogramming.com/cplusplus-programming/149549-lowest-score-drop-assignment.html

マイコード:

double findLowest(double a, double b, double c, double e, double f) 
{ 
    // creating an array numberRange[] to read the 5 input double 
    //values 
    double numberRange[5] = {a,b,c,e,f}; 

    // creating a variable minimum and assigning it the value of the 
    //first item in the numberRange[] array 
    double minimum = numberRange[0];  

    // looping through the numberRange array 
    for(int counter = 1; sizeof(numberRange)/sizeof(*numberRange) ; counter++) 
    // To get the number of elements in an array, you have to divide 
    // the size of the array by the size of each element 
    { 
     // checking if the numberRange value at the counter is less 
     // than the minimum value. If true, the minimum value is 
     //replaced with a new value. 
     if (numberRange[counter] < minimum) 
     { 
      minimum = numberRange[counter]; 
     } 

    } 

    return minimum; 
} 

エラー:スレッド1:EXC_BAD_ACCESS(コード= 1、アドレス= 0x7fff5fc89000)

+0

はthis..theコードをハイライト表示するためのプログラミング言語に応じて – Spidey

+0

@spideyのおかげでタグを追加してください、それは 'カウンタ<5'悪いだろう作る – asaber

答えて

1

問題はforループテストです:

for(int counter = 1; sizeof(numberRange)/sizeof(*numberRange) ; counter++) 
//   this ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ is always true! 

なぜそれをcounter < 5にしないのですか?

+0

++ Cです。また、 '1'ではなく '0'で始まる必要があります。 –

+0

OPはminを要素0に初期化するので1から始まります。 なぜ 'counter <5'が悪いのですか?関数の5つの値は、パラメータのために既にハードコーディングされています。 – TowerFan

+0

@To werFan:あなたはそれを2度ハードコーディングしているからです。それをしないでください。 D –

0

あなたのforループの停止条件はかなり珍しいです。また、1から数え始めます(なぜ0ではないのですか)。どのようにだけやって:

double numberRange[5] = {a,b,c,e,f}; 
return *std::min_element(numberRange); 
+0

OPは 'min'を初期化するために' numberRange [0] 'を使うので、比較は2番目の要素から始まります... –

+0

' * std :: min_element(std :: begin (numberRange)、std :: end(numberRange)) '? –

関連する問題