using System;
namespace MyNameSpace
{
class DeliveryCharges
{
static void Main()
{
//Declare variables
double[ , ] dblZipArray = {{40214, 5.00}, {40245, 4.85}, {40248, 2.67}, {40272, 3.79}, {40299, 5.40}, {42103, 2.30}, {42133, 4.60}, {42141, 1.00}, {42160, 1.45}, {42303, 3.60}};
double dblUserZIP;
int x;
Console.Clear();
//Ask user for zip code
Console.WriteLine("Please enter a ZIP code to view the delivery charge for that area.");
dblUserZIP = Convert.ToDouble(Console.ReadLine());
x = Array.BinarySearch(dblZipArray, dblUserZIP);
if(x < 0)
{
Console.WriteLine("ZIP Code {0} is not in our delivery area.", dblUserZIP);
}
else
{
Console.WriteLine("The price of delivery to ZIP code {0} is ${1}", dblUserZIP, dblZipArray[dblUserZIP]);
}
Console.ReadLine();
}
}
}
例如,当用户输入“42141”时,正确的输出应该说:“交付到邮政编码42141的价格是1.00美元”当编译此代码时,我收到错误。我不记得如何正确引用多维数组。请帮忙!
答案 0 :(得分:2)
首先,它不是编译,因为你必须使用[x,y]来访问多维数组中的单个值。例如,dblZipArray [0,0]将返回40214,而dblZipArray [0,1]将返回5.00。
其次,您不能在多维数组上使用Array.BinarySearch。没有内置方法可以通过这种方式搜索二进制数组,因此您必须编写自己的搜索功能。
这里有一些可行的示例代码,虽然它可能会对用户的输入进行错误检查,但可能会使用更有效的搜索(特别是如果您知道您的邮政编码列表已排序),以及,考虑你的双数组可以用int ZipCode和double Price重写为结构或类,因为Zip是一个双重浪费空间,这使得像.length这样的函数在逻辑上更适合你的用例(带有多维数组的数组) ,它返回数组中的单元格总数,而您可能希望它返回您支持的邮政编码数量。)
编辑:正如brz在下面指出的那样,字典会更好。
static void Main()
{
//Declare variables
double[,] dblZipArray = { { 40214, 5.00 }, { 40245, 4.85 }, { 40248, 2.67 }, { 40272, 3.79 }, { 40299, 5.40 }, { 42103, 2.30 }, { 42133, 4.60 }, { 42141, 1.00 }, { 42160, 1.45 }, { 42303, 3.60 } };
double dblUserZIP;
Console.Clear();
//Ask user for zip code
Console.WriteLine("Please enter a ZIP code to view the delivery charge for that area.");
dblUserZIP = Convert.ToDouble(Console.ReadLine());
int zip;
for (zip = 0; zip < dblZipArray.Length / 2; zip++ )
{
if (dblZipArray[zip,0] == dblUserZIP)
{
break;
}
}
if (zip == dblZipArray.Length /2)
{
Console.WriteLine("ZIP Code {0} is not in our delivery area.", dblUserZIP);
}
else
{
Console.WriteLine("The price of delivery to ZIP code {0} is ${1}", dblUserZIP, dblZipArray[zip, 1]);
}
Console.ReadLine();
}
答案 1 :(得分:2)
您使用了错误的数据结构:
您必须改为使用词典:
static void Main()
{
//Declare variables
Dictionary<int, double> zipDic = new Dictionary<int, double> { { 40214, 5.00 }, { 40245, 4.85 }, { 40248, 2.67 }, { 40272, 3.79 }, { 40299, 5.40 }, { 42103, 2.30 }, { 42133, 4.60 }, { 42141, 1.00 }, { 42160, 1.45 }, { 42303, 3.60 } };
Console.Clear();
//Ask user for zip code
Console.WriteLine("Please enter a ZIP code to view the delivery charge for that area.");
var zipCode = int.Parse(Console.ReadLine());
if (!zipDic.ContainsKey(zipCode))
{
Console.WriteLine("ZIP Code {0} is not in our delivery area.", zipCode);
}
else
{
Console.WriteLine("The price of delivery to ZIP code {0} is ${1}", zipCode, zipDic[zipCode]);
}
Console.ReadLine();
}