繁体   English   中英

循环代码和do-while循环的问题(C#)

[英]Issues with looping code and do-while loops (c#)

static double calculateTotals(double a)
    {
        double transfee = a * .01;
        double total = a + transfee;
        return total;
    }

    static void Main(string[] args)
    {
        Console.WriteLine("How many dontations to process?");
        int donations = Convert.ToInt16(Console.ReadLine());
        int[] count = new int[] { donations + 1 };
        int ct = 1;
        int i = -1;
        do
        {
            Console.WriteLine("Enter name: ");
            string name = Console.ReadLine();
            Console.WriteLine("Enter donation amount: ");
            double amount = Convert.ToDouble(Console.ReadLine());
            double transfee = amount * .01;
            i++;
            ct = count[i += 1];
            Console.WriteLine(name + "\t" + amount + "\t" + transfee);
        } while (i < donations);
        Console.WriteLine("TOTALS:" + "\t" + calculateTotals(amount) + "\t" + transfee);
        Console.ReadLine();
    }
}

你好。 我是编码的初学者,因此如果尝试不当,我深表歉意。

我正在尝试制作一个记录个人捐赠金额,计算交易费用并输出每个人结果的应用程序。 最后,我将创建最后一行输出,其中将说明捐赠总额和交易费用总额。

我目前不确定如何在我的循环中正确实现数组,也不确定循环是否在总体上得到了优化。

同样,我是初学者。 我为此类代码表示歉意,但我希望对这些内容进行一些说明。

谢谢!

首先,您的数组声明语法错误。 看到这个链接

因此应为int[] count = new int[donations+1];

其次,您需要在循环外声明并实例化数量和流量变量。

        double transfee = 0.0F;
        double amount = 0.0F;
        do
        {
            ...
            amount = Convert.ToDouble(Console.ReadLine());
            transfee = amount * .01;
            ...
        } while (i < donations);

这应该是足够的信息,可以让您再次尝试。 既然您正在学习,我认为没有人会真正为您提供答案,而您所做的工作正是您要设法解决的:)

您的代码:

        int i = -1;

        do
        {
            ...

            i++;
            ct = count[i += 1];
            ...

        } while (i < donations);

您实际上将i增大了两倍 ,然后从count [i]中获取分配给ct变量的值

看到这个例子:

        int[] count = new int[3];
        count[0] = 0;
        count[1] = 1;
        count[2] = 2;

        int i = -1;
        do
        {
            i++;
            int x = count[i += 1];
            Console.WriteLine(x);
        } while (i < 3);

它将导致IndexOutOfRangeException

说明:

第一循环:

i++;                   // i increased 1, so i = 0
int x = count[i += 1]; // i increased 1, so i = 1, then get count[1] assign to x, x is 1

第二循环:

i++;                   // i increased 1, so i = 2
int x = count[i += 1]; // i increased 1, so i = 3, then get count[3] assign to x

count [3]导致IndexOutOfRangeException

像count [i + = 1]之类的东西会使您的代码更难以维护,我认为,如果可能的话,应避免使用它,并尝试尽可能地将其写得很明确。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM