c# - 用C#制作星形金字塔

标签 c#

所以我尝试用 C# 制作金字塔,但无法正确打印它。 我正在为我学校的 C# 类(class)做这个,我真的不知道如何正确地获取金字塔中的空间。我觉得我真的做错了什么。

我得到的不是三角形,而是这样的:

   *
   **
  ***
  ****
 *****
 ******
*******
********

这是我的代码:

using System;

namespace Pyramidi
{
    class Ohjelma
    {
        static void Main()
        {
            int korkeusMax = 0;
            int valit = 0;
            do
            {
                Console.Write("Anna korkeus: ");            
                korkeusMax = Convert.ToInt32(Console.ReadLine());           
                if (korkeusMax > 0) {
                    break;
                }
                else {
                    continue;
                }          
            }
            while(true);

            for (int korkeus = 1; korkeus <= korkeusMax; korkeus++)
            {

                valit = (korkeusMax - korkeus) / 2;
                for (int i = 0; i < valit; i++)
                {
                    Console.Write(" ");
                }
                for (int leveys = 1; leveys <= korkeus; leveys++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }

                Console.ReadLine();
        }
    }
}

最佳答案

试试这个:

for (int korkeus = 0; korkeus < korkeusMax; korkeus++)
{
    for (int i = 0; i < (korkeusMax - korkeus - 1); i++)
    {
        Console.Write(" ");
    }
    for (int i = 0; i < (korkeus * 2 + 1); i++)
    {
        Console.Write("*");
    }
    Console.WriteLine();
}

或者,您可以使用new String('*', num)来代替循环。试试这个:

for (int korkeus = 0; korkeus < korkeusMax; korkeus++)
{

    Console.Write(new String(' ', korkeusMax - korkeus - 1));
    Console.Write(new String('*', korkeus * 2 + 1));
    Console.WriteLine();
}

关于c# - 用C#制作星形金字塔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22901673/

相关文章:

c# - 从给定文本中查找匹配的第一个单词 - 正则表达式

c# - Google Weather API 请求不起作用。给出请求超时

c# - 为什么我无法访问另一个表单上的文本框?

c# - 使用 WebProxy 时 HttpWebRequest 的奇怪行为

C# LINQ 按错误排序

c# - 数据集教程

c# - 如何获取datagridview当前行列值?

c# - 使用 linq 从日期中减去天数

c# - 提高生成列表的性能

c# - 如何在 C# 中实现通用缓存管理器