这是我目前的代码:
string userName = "";
int v1 = 0, v2 = 0, v3 = 0, v4 = 0, v5 = 0;
int sum = 0;
float avg;
float variance;
Console.WriteLine("Please enter your name:");
userName = Console.ReadLine();
Console.WriteLine("Please enter in a number between 10 and 50: ");
int inputCheck = 0;
inputCheck = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i <= v5; i++)
{
if (i == v1)
{
v1 = inputCheck;
if (v1 < 10 || v1 > 50)
{
Console.WriteLine("The number you have entered is invalid please enter a new variable: ");
}
continue;
}
if (i == v2)
{
v2 = inputCheck;
if (v2 < 10 || v2 > 50)
{
Console.WriteLine("The number you have entered is invalid please enter a new variable: ");
}
continue;
}
if (i == v3)
{
v3 = inputCheck;
if (v3 < 10 || v3 > 50)
{
Console.WriteLine("The number you have entered is invalid please enter a new variable: ");
}
continue;
}
if (i == v4)
{
v4 = inputCheck;
if (v4 < 10 || v4 > 50)
{
Console.WriteLine("The number you have entered is invalid please enter a new variable: ");
}
continue;
}
if (i == v5)
{
v5 = inputCheck;
if (v5 < 10 || v5 > 50)
{
Console.WriteLine("The number you have entered is invalid please enter a new variable: ");
}
continue;
}
我正在让控制台正确识别出如果v1大于50或小于10,它会给出消息。但代码停止并且不继续要求变量。我试过跟踪for循环和if循环中发生的事情,但我只是迷路了。我的任务是使用循环和一个console.readlin();来获取5个变量。如果这对我提出这个问题的原因有帮助的话。
答案 0 :(得分:2)
循环中出现一些错误:
for (int i = 0; i <= v5; i++)
因为v5 = 0,循环只会运行一次
inputCheck = Convert.ToInt32(Console.ReadLine());
只读取一次数字,即使您修改了循环以运行5 times
,用户提出的输入也只会一次,因此需要移动{{} 1}}在循环中。
可以在循环中改进1到50的输入检查,因为对所有变量都有相同的限制。
尝试这种方式:
inputCheck = Convert.ToInt32(Console.ReadLine());
答案 1 :(得分:2)
如果您想再次输入,则需要将Console.WriteLine("Please enter your name:");
和userName = Console.ReadLine();
放在for
循环的开头。
答案 2 :(得分:2)
好吧,看起来v5
为0,所以你的循环只运行一次!
for (int i = 0; i <= v5; i++) //this will be true only once because v5 = 0
答案 3 :(得分:2)
您的代码存在一些问题。正如其他人指出的那样,
int v5 = 0;
for (int = 0; i < v5; i++) ...
意味着您永远不会进入for循环,因为i < v5
是false
。
其次,您似乎试图将v1
- v5
作为变量进行循环。这不是
在任意数量的变量上执行循环的正确方法。您将需要一个数组或其他类型的集合。
你想要的可能是这样的:
string userName = "";
int[] v= new int[5];
int sum = 0;
float avg;
float variance;
Console.WriteLine("Please enter your name:");
userName = Console.ReadLine();
Console.WriteLine("Please enter in a number between 10 and 50: ");
for (int i = 0; i < v.Length; i++)
{
int inputCheck = Convert.ToInt32(Console.ReadLine());
while (inputCheck < 10 || inputCheck > 50)
{
Console.WriteLine("The number you have entered is invalid please enter a new variable: ");
inputCheck = Convert.ToInt32(Console.ReadLine());
}
v[i] = inputCheck;
}
答案 4 :(得分:0)
for (int i = 0; i <= v5; i++)
{
if (i == v1)
{
v1 = inputCheck;
if (v1 < 10 || v1 > 50)
{
Console.WriteLine("The number you have entered is invalid please enter a new variable: ");
}
continue;
}
...
}
循环只有第一次迭代。
因为在第一次迭代中有continue;
。
v5
将始终为0。i
将在首先continue;
之后更改为1,然后i <= v5
- false(1> 0 :)),并且循环将完成