我很沮丧。我是一个新手做我的作业我似乎无法弄清楚为什么我的消息框只显示相同的数字(计算的最后一个小计数)五次。我不明白如何使用for循环将我的值存储到数组中而不重置它。有人能帮忙吗?提前谢谢。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace InvoiceTotal
{
public partial class frmInvoiceTotal : Form
{
public frmInvoiceTotal()
{
InitializeComponent();
}
// TODO: declare class variables for array and list here
decimal[] decArray = new decimal[5];
int intIndex = 0;
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
if (txtSubtotal.Text == "")
{
MessageBox.Show(
"Subtotal is a required field.", "Entry Error");
}
else
{
decimal subtotal = Decimal.Parse(txtSubtotal.Text);
if (subtotal > 0 && subtotal < 10000)
{
decimal discountPercent = 0m;
if (subtotal >= 500)
discountPercent = .2m;
else if (subtotal >= 250 & subtotal < 500)
discountPercent = .15m;
else if (subtotal >= 100 & subtotal < 250)
discountPercent = .1m;
decimal discountAmount = subtotal * discountPercent;
decimal invoiceTotal = subtotal - discountAmount;
discountAmount = Math.Round(discountAmount, 2);
invoiceTotal = Math.Round(invoiceTotal, 2);
txtDiscountPercent.Text = discountPercent.ToString("p1");
txtDiscountAmount.Text = discountAmount.ToString();
txtTotal.Text = invoiceTotal.ToString();
for (intIndex = 0; intIndex <= decArray.Length - 1; intIndex++)
{
decArray[intIndex] = invoiceTotal;
}
}
else
{
MessageBox.Show(
"Subtotal must be greater than 0 and less than 10,000.",
"Entry Error");
}
}
}
catch (FormatException)
{
MessageBox.Show(
"Please enter a valid number for the Subtotal field.",
"Entry Error");
}
txtSubtotal.Focus();
}
private void btnExit_Click(object sender, EventArgs e)
{
// TODO: add code that displays dialog boxes here
string totalstring = "";
foreach (decimal value in decArray)
{
totalstring += value + "\n";
}
MessageBox.Show(totalstring + "\n", "Order Totals");
this.Close();
}
} }
答案 0 :(得分:0)
由于它是一个作业,我只能给你一个线索,你的循环目前只有一个invoiceTotal
,你根本不必使用循环,当你的控制进入{{1} }事件然后在计算btnCalculate_Click
后,您可以使用您的班级invoiceTotal
将其放入decArray
。增加intIndex
并在输入intIndex
中的值之前,您必须检查decArray
是否小于intIndex
。另一个想法是,如果您期望未知数量的输入,则使用array length
而不是数组。
答案 1 :(得分:0)
您的for...loop
将数组的每个索引设置为总数。
for (intIndex = 0; intIndex <= decArray.Length - 1; intIndex++)
{
decArray[intIndex] = invoiceTotal;
}
问问自己:它的目的是什么?您可以安全地将其更改为:
decArray[intIndex++] = invoiceTotal;
我将由你决定如何改变它(因为它是家庭作业)。