C# 在数组中查找两个数字,使其和等于用户给定的数字
我知道这个问题在社会上已经被问过很多次了。即使在使用c#库函数之后,我的代码也无法工作,并且显示所有索引都不存在这样的对C# 在数组中查找两个数字,使其和等于用户给定的数字,c#,arrays,algorithm,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,i
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();
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
名称空间测试
{
班级计划
{
静态void Main(字符串[]参数)
{
int i、nts、index1、index2;
随机rnd=新随机();
整数[]个数=新整数[10];
对于(i=0;i<10;i++)
数字[i]=rnd.Next(200984);
数组。排序(数字);
对于(i=0;i<10;i++)
{
控制台。写入(数字[i]+“”);
}
Console.WriteLine(“\n输入要搜索的总和”);
nts=Console.Read();
对于(index1=0;index1来说,您解决问题的算法很好,问题在于读取数字。因此,您实际上找到了错误的值
Console.Read()
从标准输入流读取下一个字符。(ntp中的ASCII值)
您确定可以在数组中找到您查找的总和吗?您的数组非常小(10个数字),范围非常大(在200和984之间)。您是否使用较小的范围(例如,在1和10之间)进行过测试?是的,但问题仍然存在。rnd.Next(200984)从测试方法开始,它将通过带有已知数字的硬编码数组和已知的“和”来知道期望的结果。随机数提供随机结果(除非你使用<代码>随机< /代码>错误,这不是你的情况)。这救了一天!我的坏。
nts = Convert.ToInt32(Console.ReadLine());