我具有以下列表:列表對齊,最簡單的方法來實現
100 - > 1.0 99
- > 1.1 98
- > 1.1 97
- > 1.2 ...
23-28 - > 5.6
...
0-5 - > 6.0
在左側是最大達到了點,右側的檔次。 此列表包含大約40個不同的點 - >等級。所以我的計劃是計算考試的分數,最後應該說100分達到了,你的分數達到了1.0 ... 3達到的分數 - > 6.0 ...
根據我目前的知識,我知道只有開關情況,但我認爲這不是實現它的最好方法。
我具有以下列表:列表對齊,最簡單的方法來實現
100 - > 1.0 99
- > 1.1 98
- > 1.1 97
- > 1.2 ...
23-28 - > 5.6
...
0-5 - > 6.0
在左側是最大達到了點,右側的檔次。 此列表包含大約40個不同的點 - >等級。所以我的計劃是計算考試的分數,最後應該說100分達到了,你的分數達到了1.0 ... 3達到的分數 - > 6.0 ...
根據我目前的知識,我知道只有開關情況,但我認爲這不是實現它的最好方法。
我與你有列表中的數據結構開始。 (這是假設C#6,順便說一句 - 早期版本的C#,你將無法使用自動實現的只讀屬性,但是這是他們唯一的區別)
public sealed class GradeBand
{
public int MinScore { get; }
public int MaxScore { get; } // Note: inclusive!
public decimal Grade { get; }
public GradeBand(int minScore, int maxScore, decimal grade)
{
// TODO: Validation
MinScore = minScore;
MaxScore = maxScore;
Grade = grade;
}
}
您可以構建你的列表與:
var gradeBands = new List<GradeBand>
{
new GradeBand(0, 5, 6.0m),
...
new GradeBand(23, 28, 5.6m),
...
new GradeBand(100, 100, 1.0m),
};
你可能會想某種驗證,樂隊覆蓋整個檔次範圍。
再就是尋找的二級相當明顯的選擇。首先,沒有預處理的線性掃描:
public decimal FindGrade(IEnumerable<GradeBand> bands, int score)
{
foreach (var band in bands)
{
if (band.MinScore <= score && score <= band.MaxScore)
{
return band.Grade;
}
}
throw new ArgumentException("Score wasn't in any band");
}
或者你可以預處理帶一次:
var scoreToGrade = new decimal[101]; // Or whatever the max score is
foreach (var band in bands)
{
for (int i = band.MinScore; i <= band.MaxScore; i++)
{
scoreToGrade[i] = band.Grade;
}
}
然後對每個分數你可以使用:
decimal grade = scoreToGrade[score];
嘗試該樣品
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<int, double> dictionary =
new Dictionary<int, double>();
dictionary.Add(100, 1.0);
dictionary.Add(99, 1.1);
//Add more item here
// See whether Dictionary contains a value.
if (dictionary.ContainsKey(100))
{
double value = dictionary[100];
Console.WriteLine(String.Format("{0:0.0}",value));
}
Console.ReadLine();
}
}
正如我上面顯示的,我有例如28-23分相同的成績。所以這不是正確的解決方案。 – Matej
@Matej:那樣會很好 - 你只需要'dictionary.Add(23,5.6); dictionary.Add(24,5.6);'等等。但是當你有一組從0開始的連續整數密鑰時,真的不需要使用字典... –
「5,6」意思是「5.6」作爲一個單一的值,還是這是別的?你說你有一個列表 - 你有什麼樣的數據結構? –
其5.6,我編輯了我的帖子。我只有一份上面列出的文件,我沒有計劃以哪種方式構建它,以便輕鬆訪問。 – Matej
對。現在,這裏的表現有多重要?編寫*簡單*代碼來實現這一點非常容易... –