晚安编码员 - 对于我在软件开发类中的任务,我必须嵌套while循环。对于外循环,我必须从5倒数到1,内循环我必须以0为增量从0到10计数。我的问题是我看到一个和两个没有错误,我今晚上课和讲师审查了程序,代码完全相同。外循环的输出是正确的,但是内循环的输出似乎从4开始,当它应该从0开始,跳过2.当代码清楚地指出时,内循环也计数到12我试图宣布" i"变量为0,结果相同。这就是为什么我认为这是一个错误。我对编码很新,所以我不熟悉使用bug工具。非常感谢您的意见! :)
{
class Program
{
static void Main(string[] args)
{
int k = 5; //assigned variable for 1st loop
int i; //assigned variable for 2nd loop
while (k > 0) //run first loop as long as "k" is greater than 0
{
i = 0;//set i variable to 0
while (i <= 10)//run second loop as long as "i" is greater than or equal to 10
//second loop runs until first loop is over
{
i += 2;//count "i" varible in increments of 2
Console.WriteLine("k= {0} i= {1} ", k, i);//print index value for both variables
}
k--;//subtract "k" variable by increment of 1
}
}
}
}
下面是预期的输出(记事本)和我收到的输出(VB)。
答案 0 :(得分:2)
对于内部循环,您在写入行之前递增i,因此它将永远不会打印0(每个内部循环立即从2开始)。扭转这些界限:
Console.WriteLine("k= {0} i= {1} ", k, i);
i += 2;
答案 1 :(得分:0)
Ruby版本:
k = 5
while k > 0
i = 0
while i <= 10
puts "k = #{k}: i = #{i}"
i += 2
end
k -= 1
end