[英]The name 'dx' doesn't exist in the current context in a do while loop
在我的代码开始时,我有一个小问题。 代码如下:
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”在当前上下文中不存在。 我该怎么办? 还是整个代码是错误的?
您应该在循环外创建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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.