在数组中查找两个数字,使得它们的总和等于用户给出的数字

时间:2014-08-31 06:01:46

标签: c# arrays algorithm

我知道这个问题在社区中被多次提出过。即使在使用c#库函数之后,我的代码也不起作用,并且显示没有所有索引都存在这样的对。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace test
{
class Program
{
    static void Main(string[] args)
    {
        int i, nts, index1,index2;
        Random rnd = new Random();
        int[] numbers = new int[10];
        for (i = 0; i < 10; i++)
            numbers[i] = rnd.Next(200, 984);
        Array.Sort(numbers);
        for (i = 0; i < 10; i++)
        {
            Console.Write(numbers[i] + " ");

        }
        Console.WriteLine("\nEnter the sum to search\n");
        nts = Console.Read();
        for(index1=0;index1<numbers.Length;index1++)
        {
            index2 = Array.BinarySearch(numbers,(nts - numbers[index1]));
            if (index2 < 0)
            {
                Console.WriteLine("No such pairs for " + index1);
                continue;
            }
            else
            {
                Console.WriteLine("Numbers found" + numbers[index1] + "and" + numbers[index2]);
                break;
            }

        }
        Console.ReadKey();
    }
}

}

1 个答案:

答案 0 :(得分:2)

你的算法解决问题很好,问题在于读取数字。所以你实际上找到了错误的价值观。

Console.Read()

从标准输入流中读取下一个字符。 (ntp中的ASCII值)

nts = Convert.ToInt32(Console.ReadLine());
相关问题