使用循环在C#中创建数字及其正方形列表

时间:2013-03-03 08:26:00

标签: c# list for-loop perfect-square

我想使用for循环在C#中列出数字及其正方形。

现在我有:

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {

            int counter;
            int square = 1;
            const int maxValue = 10;


            Console.WriteLine("Number  Square");
            Console.WriteLine("-------------------");
            {
                for (counter = 1; counter <= maxValue; counter++)
                    square = counter ^ 2;
                Console.WriteLine("{0}   {1}",  counter, square);
            }

         }
      }

   }

但我的输出只是11和8。

当我在变量声明下放置“square = counter ^ 2”时,我最终得到一列数字1-10,但第二行只是一堆三,如果它们被设置为0则它们是两个。如果我没有设置它,它也会给我一个错误来声明计数器变量。

当我把等式放在现在的位置时,它要求将方形变量声明为某个东西(在这里它是1)。

我也是初学者,我还没有学过课程,所以我更倾向于不修改课程。

编辑:修复,天哪我上次没犯错,是的,我需要更多的练习。遗憾

7 个答案:

答案 0 :(得分:2)

您不小心使用简写来声明for循环块。

for语句后面应加上花括号来表示要执行的块。但是,如果你跳过括号,它只会抓住“下一行”。在您的情况下,循环中仅执行square = counter ^ 2;。但是,^运算符用于xor运算,而不是pow。

你想要这个:

Console.WriteLine("Number  Square");
Console.WriteLine("-------------------");

for (counter = 1; counter <= maxValue; counter++)
{
    square = counter * counter;
    Console.WriteLine("{0}   {1}",  counter, square);
}

答案 1 :(得分:1)

尝试使用此计数器循环:

for (counter = 1; counter <= maxValue; counter++)
{
   square = Math.Pow(counter, 2);
   Console.WriteLine("{0}   {1}",  counter, square);
}

答案 2 :(得分:1)

括号的放置非常重要:

 Console.WriteLine("Number  Square");
 Console.WriteLine("-------------------");

 for (counter = 1; counter <= maxValue; counter++)
 {
     square = counter * counter;
     Console.WriteLine("{0}   {1}",  counter, square);
 }

注意:出于这个原因,始终为for循环和if语句使用括号大括号是一种很好的做法。

另请注意,^并非“{1}}的强大功能。但是专属OR

答案 3 :(得分:0)

^运算符不是为了这个目的。请改用System.Math.Pow()。例: var square = Math.Pow(3, 2)。这将给出9。

答案 4 :(得分:0)

square = counter ^ 2 ?? 此处^xor operation

这样做:
square = counter * counter;

并附上

{
    square = counter * counter;
    Console.WriteLine("{0}   {1}",  counter, square);
}

for - 循环内。

或者更好地使用Math.pow方法

答案 5 :(得分:0)

您的for循环处于短手模式。您的console.writeline不在for循环中。

尝试用此

替换行
for (counter = 1; counter <= maxValue; counter++)
{
  square = counter * counter;
  Console.WriteLine("{0}   {1}",  counter, square);
}

请注意,^不是C#中的幂运算符。它用于XOR。

答案 6 :(得分:0)

我会用:

    private void sqtBtn_Click(object sender, EventArgs e)
    {
        outputList.Items.Clear();

        int itemValue, sqt;

        for (int i = 0; i < randomNumAmount; i++)
        {
            int.TryParse(randomList.Items[i].ToString(), out itemValue);

            outputList.Items.Add(Math.Sqrt(itemValue).ToString("f"));
        }
    }