2016-10-30 11 views
-6

私が作成しているプログラムでは、月の量、毎月の休暇の量、1か月間の不在の量を入力するように求められます。これは、従業員の平均休暇額と許容される最大休業期間を経過した回数を計算することになっています。C#、特定の配列検索を出力するには?

私は配列ループで平均を計算することができましたが、彼が最大欠勤を過ぎた時間に問題がありました。私はバイナリ検索方法を使用していますが、従業員が許容された不在額を超えた特定の月額を出力するのに問題があります。

これは、そのセクションのための私の現在のコードです:

for (int i = 0; i < numbOfAbsences.Length; i++) 
{ 
    sum += numbOfAbsences[i]; 
    averageAbsences = (sum/numbOfMonths); 
    Console.WriteLine("Employee was absent " + averageAbsences + " times per month."); 
} 

a = Array.BinarySearch(numbOfAbsences, maxAbsences); 
if (a >= maxAbsences) 
{     
} 

私は最大量を超えたかどうかを指摘しようとしているわけではないとして、私は、括弧の最後のセットの下に行くと何が不明だが、むしろ、それがあった回数。

先進的なヘルプありがとうございます。

+0

は、あなたの平均化プログラムが正しいですか?それが完了する前に 'sum'を分割します – malioboro

答えて

0

まず、質問は明確に記載されていません。

"整数の配列を取って、それらをすべて数で割って平均の倍数配列を生成する良い方法はありますか?また、どのようにしてint配列の値をより大きく数えることができますか? (これは私がこれまで持っていたものです)」

第2に、コードスニペットは非常に混乱しています。もっと正確に言えば...正しくインデントされていません。使用されている変数のすべてが定義されているわけではないので、その変数を推測する必要があります。変数名はあまり記述的ではないので、各変数がどのようにそれを理解するのに使われているかを見なければなりません。しかし、最も重要なことに、これはカプセル化ではありません。オブジェクトはありません。関数はありません。すべての行を非常に注意深く読んで理解する必要のある生のコードです。

コントラストこれでスニペットは:

using System; 
using System.Linq; 

namespace ArraySearch_StackOverflow 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      int[] employeeAbsencesEachMonth = new int[] { 1, 2, 3, 4, 5, 6 }; 
      int maxAbsencesAllowedPerMonth = 3; 

      double averageAbsencesPerMonth = GetAverageAbsencesPerMonth(employeeAbsencesEachMonth); 
      Console.WriteLine($"Employee's Average Absences Per Month: {averageAbsencesPerMonth}"); /* 3 */ 
      int numTimesMaxAbsencesExceeded = GetNumMaxAbsencesViolations(employeeAbsencesEachMonth, maxAbsencesAllowedPerMonth); 
      Console.WriteLine($"Number of Times Employee Exceeded Max Absence Limit: {numTimesMaxAbsencesExceeded}"); /* 3 */ 

      Console.WriteLine("\nPress any key to continue..."); 
      Console.ReadKey(); 
     } 

     private static double GetAverageAbsencesPerMonth(int[] employeeAbsencesEachMonth) 
     { 
      // ??? 
      throw new NotImplementedException(); 
     } 

     private static int GetNumMaxAbsencesViolations(int[] employeeAbsencesEachMonth, int maxAbsencesAllowedPerMonth) 
     { 
      // ??? 
      throw new NotImplementedException(); 
     } 
    } 
} 

このコードは非常に明確です。説明がなくても、何が尋ねられているのか、答えが正しいかどうかをどうやって判断するのかはすぐに分かります。質問が関数シグネチャに変換され、コンテキストがドライバが関数が呼び出されるように変換されたため、セットアップと期待される結果が得られます。

手際よく、これはあなたがコピー&ペーストすることができ、それを直接あなたのコードにチャンスを作る、答えのための簡単な形式を意味します

private static double GetAverageAbsencesPerMonth(int[] employeeAbsencesEachMonth) 
{ 
    return employeeAbsencesEachMonth.Sum()/employeeAbsencesEachMonth.Length; 
} 

private static int GetNumMaxAbsencesViolations(int[] employeeAbsencesEachMonth, int maxAbsencesAllowedPerMonth) 
{ 
    return employeeAbsencesEachMonth.Count(x => x > maxAbsencesAllowedPerMonth); 
} 
関連する問題