[英]The name 'dx' doesn't exist in the current context in a do while loop
I have a little problem at the beggining of my code. 在我的代码开始时,我有一个小问题。 The code is the following:
代码如下:
do
{
Console.Write("x = ");
string x = Console.ReadLine();
double dx = Convert.ToDouble(x);
Console.Write("X must be bigger than 1.");
}
while (dx > 1);
I want my program to ask for x, until it's bigger than 1. The problem is, at the while part of the code, I'm getting this: 我希望我的程序要求x,直到它大于1。问题是,在代码的同时,我得到了这个:
The name 'dx' doesn't exist in the current context. 名称“ dx”在当前上下文中不存在。 What should I do?
我该怎么办? Or the whole code is wrong?
还是整个代码是错误的?
You should create dx
outside loop, because variable is not visible outside { }
: 您应该在循环外创建
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);
Also, you can refactor your code a little: 此外,您可以稍微重构代码:
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.