这是我的代码块,我无法弄清楚如何使周长和体积执行计算。例如,当我为前4个参数输入1,1,1,1时,我得到0,0表示体积和周长。
if (packages == 1)
{
int width = 0, length = 0, height = 0, weight = 0;
int volume = 0, girth = 0;
int[] packageInfo = new int[6] { width, length, height, weight ,volume, girth };
packageInfo[4] = height * width * length;
packageInfo[5] = (2 * length + 2 * width);
double packageSum = 0;
for (int k = 0; k < 4; k++)
{
string line = Console.ReadLine();
if (!int.TryParse(line, out packageInfo[k]))
{
Console.WriteLine("Couldn't parse {0} - please enter integers", line);
k--;
}
}
if(packageInfo[3] > 25)
{
packageSum = 0;
Console.WriteLine("Package couldn't be shipped because of its size.");
}
if (volume > 4800)
{
packageSum = packageSum + 5.95;
}
if (volume > 9600)
{
packageSum = 0;
Console.WriteLine("Package couldn't be shipped because of its size.");
}
foreach (var item in packageInfo)
Console.WriteLine(item.ToString());
}
答案 0 :(得分:1)
您应该在获得用户输入后计算它们。以这种方式重新排列代码:
for (int k = 0; k < 4; k++)
{
string line = Console.ReadLine();
if (!int.TryParse(line, out packageInfo[k]))
{
Console.WriteLine("Couldn't parse {0} - please enter integers", line);
k--;
}
}
packageInfo[4] = packageInfo[0] * packageInfo[1] * packageInfo[2];
packageInfo[5] = (2 * packageInfo[0] + 2 * packageInfo[1]);
答案 1 :(得分:1)
C#中的变量与数学中的变量不同。据我所知,每当packageInfo[4]
被修改时,您都希望packageInfo[0], packageInfo[1], packageInfo[2]
更新。因为,在数学中,如果将体积定义为高度*宽度*长度并修改任何这些变量,则卷会更改。不幸的是,C#中的“标准变量”只是一小块。你从它读/写。我不是很精确(我不是那么精通语言),但是没有变量的概念被别人定义(它们只能用一些值初始化,这可能是其他变量的值) )。要创建这样的关系,需要语言结构来表示它们。
所以你的代码目前所做的是:
Console
的输入时,packageInfo[0], packageInfo[1], packageInfo[2], packageInfo[3]
会被修改。packageInfo[0]
,则不会修改int
packageInfo[]
您可以使用类似以下内容来模拟与数学更相似的行为:
private int _height;
private int _width;
private int _length;
private int Volume =
{
get { return _height * _width * _length };
}
答案 2 :(得分:0)
仔细查看您的代码。
首先,你这样做:
int width = 0, length = 0, height = 0, weight = 0;
int volume = 0, girth = 0;
int[] packageInfo = new int[6] { width, length, height, weight ,volume, girth };
packageInfo[4] = height * width * length;
packageInfo[5] = (2 * length + 2 * width);
double packageSum = 0;
0 * 0 * 0 = 0。
2 * 0 + 2 * 0 = 0
然后,在之后你计算了音量和周长,你实际上是在询问用户的输入:
for (int k = 0; k < 4; k++)
{
string line = Console.ReadLine();
if (!int.TryParse(line, out packageInfo[k]))
{
Console.WriteLine("Couldn't parse {0} - please enter integers", line);
k--;
}
}