21xrx.com
2024-06-03 06:42:43 Monday
登录
文章检索 我的文章 写文章
如何使用C++的for语句输出图形?
2023-07-09 08:12:38 深夜i     --     --
C++ for 输出 图形 语句

在C++语言中,使用for循环语句可以方便地输出具有规律的图形。以下是一些使用for语句输出图形的示例:

示例1:输出正方形


#include <iostream>

using namespace std;

int main() {

  int n;

  cout << "请输入正方形的边长:";

  cin >> n;

  for (int i = 1; i <= n; i++) {

    for (int j = 1; j <= n; j++) {

      cout << "* ";

    }

    cout << endl;

  }

  return 0;

}

示例2:输出直角三角形


#include <iostream>

using namespace std;

int main() {

  int n;

  cout << "请输入直角三角形的高度:";

  cin >> n;

  for (int i = 1; i <= n; i++) {

    for (int j = 1; j <= i; j++) {

      cout << "* ";

    }

    cout << endl;

  }

  return 0;

}

示例3:输出倒直角三角形


#include <iostream>

using namespace std;

int main() {

  int n;

  cout << "请输入倒直角三角形的高度:";

  cin >> n;

  for (int i = n; i >= 1; i--) {

    for (int j = 1; j <= i; j++) {

      cout << "* ";

    }

    cout << endl;

  }

  return 0;

}

示例4:输出菱形


#include <iostream>

using namespace std;

int main() {

  int n;

  cout << "请输入菱形的边长:";

  cin >> n;

  for (int i = 1; i <= n; i++) {

    for (int j = 1; j <= n - i; j++)

      cout << " ";

    

    for (int j = 1; j <= 2 * i - 1; j++) {

      cout << "* ";

    }

    cout << endl;

  }

  for (int i = n - 1; i >= 1; i--) {

    for (int j = 1; j <= n - i; j++)

      cout << " ";

    

    for (int j = 1; j <= 2 * i - 1; j++) {

      cout << "* ";

    }

    cout << endl;

  }

  return 0;

}

这些示例代码演示了使用for语句输出不同形状和大小的图形的方法。通过使用循环嵌套的方式,我们可以轻松地控制图形的大小和形状。

对于初学者来说,理解和掌握for语句的用法是很重要的。因为在实际的编程中,我们常常需要使用循环语句来实现各种计算和功能,而for语句是其中比较重要的一种。所以,我们要认真学习和掌握for语句的用法,以便更好地运用到实际编程中。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复