2016-05-15 111 views
0

我有一些这样的代码行。 任何人都可以为我解释为什么“while循环”不停止。它保持显示比平衡更多的结果。为什么我的“while循环”不停止

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(); 
} 
+3

它完全是你写的。当a大于余额时,循环结束,然后打印出比平衡大的人。你期望在这里发生什么? – Steve

+0

那是因为你没有增量。基本上a总是零而不会上升。 – ARLCode

+0

它应该运行3次。 – Jerfov2

回答

1

正在检查的值之后加那么它首先添加然后检查是否a大于balance或不那么一次额外phoneprice中加入a。让你的时间循环

while ((a + phonePrice) < balance) 
    { 
    a = a + phonePrice; 
    } 
+0

谢谢,我现在明白了 – kaynb

3

它确实是你写的。
循环结束时,一个比平衡更大,那么你打印一个变量

如果你希望停止循环之前钱用完了,那么你需要改变循环退出条件

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(); 
} 
+0

谢谢,我现在明白了 – kaynb