为数字赋予不同的值

时间:2012-12-27 11:04:38

标签: c#

我在这里有点困惑,虽然我确信答案很简单。我想为不同的数字添加不同的值,但是如何才能简单地实现呢?

示例:1 = 10,3 = 20,5 = 30.如果用户输入数字4,答案将是60.因为2没有任何特定值,所以它也应该是10.数字2也需要10作为一个值,因为它在1之后,并没有得到新的值。值在3到20之间变化,从那时起在20之后的每个数字的值上变化,直到将新值分配给更高的数字。然后数字4需要再次为20,因为值尚未改变,数字5需要得到值50.

另一个例子:

    Numers entered by user: 10

    Values:
    1 = 10
    5 = 20
    8 = 30

    In this case, the values of all the 10 numbers should be:
    1 = 10
    2 = 10
    3 = 10
    4 = 10
    5 = 20
    6 = 20
    7 = 20
    8 = 20
    9 = 30
    10 = 30

所以答案是:180(所有组合值)。

3 个答案:

答案 0 :(得分:3)

我认为您可以使用Dictionary<int, int>,因此key将是用户输入,value - 相关的“响应”。

IDictionary<int, int> map = new Dictionary<int, int>();
map.Add(1, 10);
map.Add(3, 20);


public int GetResponseForUserInput(int input)
{
   int response = -1;
   if (map.ContainsKey(input))
   {
      response = map[input];
   }

   return response;
}

答案 1 :(得分:1)

您的示例包含棘手的错误:8 = 20应该8 = 30而不是190,所以实际答案是// Following lines should be replaced with actual input method int TotalNumber = 10; List<Tuple<int, int>> CheckPoints = new List<Tuple<int, int>>(); CheckPoints.Add(Tuple.Create(1, 10)); CheckPoints.Add(Tuple.Create(5, 20)); CheckPoints.Add(Tuple.Create(8, 30)); int NumberTillCount = 10;//determines point till which calculation should proceed int result = 0; Tuple<int, int> CurrentCheckPoint = new Tuple<int,int>(0,0); //Loop checks if new CheckPoint is encountered and writes it in temp variable 'CurrentCheckPoint' for (int i = 1; i <= NumberTillCount; i++) { CurrentCheckPoint = CheckPoints.FindIndex(x=>x.Item1 == i) != -1 ? CheckPoints.Find(x=>x.Item1 == i) : CurrentCheckPoint; result += CurrentCheckPoint.Item2; }

以下是根据您的样本计算总计的代码。希望它有所帮助

{{1}}

答案 2 :(得分:0)

你能做的最简单的事情可能是实现一个带开关结构的方法,如下所示:

public int getNumber(int inputNr)
{
    var returnNr = 1;

    switch (inputNr)
    {
        case 1:
            returnNr = 10;
            break;
        case 3:
            returnNr = 30;
            break;
        case 4:
            returnNr = 60;
            break;
        default:
            // Probably not needed, as default returnNr is 1.
            break;
    }

    return returnNr;
}

编辑:再想一想,这更容易:

// Place the values in positions according to when you want them as results:
int[] numbers = {1, 10, 1, 30, 60};  

public int getNumber(int inputNr){
    return numbers.GetValue(inputNr); // Return the value at position "inputNr".
}