-5

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

示例: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(所有组合值)。

4

3 回答 3

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;
}
于 2012-12-27T11:06:34.507 回答
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;
}
于 2012-12-27T13:22:51.660 回答
0

The simplest thing you could do is probably to just implement a method with a switch-structure, like this:

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;
}

Edit: On second thought, this is even easier:

// 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".
}
于 2012-12-27T11:14:23.643 回答