为什么我的" while循环"不停

时间:2016-05-15 20:18:38

标签: c# while-loop

我有一些像这样的代码。 任何人都可以为我解释为什么" while loop"不停。它保持显示的结果超过平衡。

static void Main(string[] args)
{
    const double balance = 303.91;
    const double phonePrice = 99.99;
    double a = 0;

    while (a < balance )
    {
        a = a + phonePrice; 
    }
    Console.WriteLine(a);
    Console.ReadLine();
}

2 个答案:

答案 0 :(得分:3)

它完全符合您所写的内容 当a大于balance时,循环结束,然后打印变量

如果您希望在用完资金之前停止循环,那么您需要更改循环退出条件

static void Main(string[] args)
{
    const double balance = 303.91;
    const double phonePrice = 99.99;
    double a = 0;

    // You don't want to run out of money, so check if buying 
    // another phone will bankrupt your finances....
    while ((a + phonePrice) < balance )
    {
        a = a + phonePrice; 
    }
    Console.WriteLine(a); // a = 299,97
    Console.ReadLine();
}

答案 1 :(得分:1)

您正在检查添加后的值,因此首先添加,然后检查 int w = 0; int h = 0; foreach (Control x in Tab_Control.Controls) { if (x.Bounds.Right > w) w = x.Bounds.Right; if (x.Bounds.Bottom > h) h = x.Bounds.Bottom; } Tab_Control.Size = new Size(w, h); Form1.Size = new Size(w, h); 是否大于a,以便balance添加一次额外的手机价格。做你的while循环

a
相关问题