0

全部。这里的学生程序员,不仅仅是一个菜鸟,而是在数组方面苦苦挣扎。我有一个家庭作业,几周前我上交了一半的分数,因为我无法让并行阵列工作。我们被要求创建一个 GUI 来计算六个不同区号的电话费用。GUI 要求输入区号(您会获得要输入的有效代码列表)和通话时长。我认为我的问题在于让程序循环遍历区域代码数组,但我完全不知道从这里去哪里。(我还敢打赌,当我看到答案可能是什么时,我会脸色难看。)这是我的 GUI 按钮代码。无论我输入什么区号,它都会返回 1.40 美元的成本。感谢您的关注!

private void calcButton_Click(object sender, EventArgs e)
    {
        int[] areaCode = { 262, 414, 608, 715, 815, 902 };
        double[] rates = { 0.07, 0.10, 0.05, 0.16, 0.24, 0.14 };
        int inputAC;
        double total = 0;

        for (int x = 0; x < areaCode.Length; ++x)
        {

            inputAC = Convert.ToInt32(areaCodeTextBox.Text);

            total = Convert.ToInt32(callTimeTextBox.Text) * rates[x];
            costResultsLabel.Text = "Your " + callTimeTextBox.Text + "-minute call to area code " + areaCodeTextBox.Text + " will cost " + total.ToString("C");


        }
    }
4

1 回答 1

0

试试这个

private void calcButton_Click(object sender, EventArgs e)
{
    int[] areaCode = { 262, 414, 608, 715, 815, 902 };
    double[] rates = { 0.07, 0.10, 0.05, 0.16, 0.24, 0.14 };
    if(!string.IsNullOrEmpty(areaCodeTextBox.Text))
    {
        double total = 0;
        if(!string.IsNullOrEmpty(callTimeTextBox.Text))
        {
            int index = Array.IndexOf(areaCode, int.Parse(areaCodeTextBox.Text)); //You can use TryParse to catch for invalid input
            if(index > 0)
            {
                total = Convert.ToInt32(callTimeTextBox.Text) * rates[index];
                costResultsLabel.Text = "Your " + callTimeTextBox.Text + "-minute call to area code " + areaCodeTextBox.Text + " will cost " + total.ToString("C");
            }
            else
            {
                //Message Area code not found  
            }
        }
        else
        {
            //Message Call time is empty
        }
    }
    else
    {
        //Message Area Code is empty
    }
}

或者,如果给你一个任务,你必须展示如何跳出循环,那么你当前代码中需要的只是添加一个条件

private void calcButton_Click(object sender, EventArgs e)
{
    int[] areaCode = { 262, 414, 608, 715, 815, 902 };
    double[] rates = { 0.07, 0.10, 0.05, 0.16, 0.24, 0.14 };
    int inputAC;
    double total = 0;

    for (int x = 0; x < areaCode.Length; ++x)
    {    
        inputAC = Convert.ToInt32(areaCodeTextBox.Text);
        total = Convert.ToInt32(callTimeTextBox.Text) * rates[x];

        if(inputAC == areaCode[x]) //ADDED condition
            break;
    }
    costResultsLabel.Text = "Your " + callTimeTextBox.Text + "-minute call to area code " + areaCodeTextBox.Text + " will cost " + total.ToString("C");
}
于 2017-10-20T02:47:29.300 回答