2017-02-18 77 views
0

在我的代碼開始時有一點問題。代碼如下:do while while循環中當前上下文中不存在名稱'dx'

do 
{ 
    Console.Write("x = "); 
    string x = Console.ReadLine(); 
    double dx = Convert.ToDouble(x); 
    Console.Write("X must be bigger than 1."); 
} 
while (dx > 1); 

我想我的程序,要求X,直到它比1.更大的問題是,在代碼的一部分時,我得到這個:

名稱'dx'在當前上下文中不存在。 我該怎麼辦?或者整個代碼錯了?

回答

0

您應該創建dx外循環,因爲變量是不可見的外{ }

double dx; 
do 
{ 
    Console.Write("x = "); 
    string x = Console.ReadLine(); 
    dx = Convert.ToDouble(x); 
    Console.Write("X must be bigger than 1."); 
} 
while (dx > 1); 

此外,您還可以重構你的代碼一點點:

double dx; 
do 
{ 
    Console.Write("x = "); 
    dx = Convert.ToDouble(Console.ReadLine()); //you can get exception here if your line can't be converted to double 
    Console.Write("X must be bigger than 1."); 
} 
while (dx > 1);