发表日期: 2022-07-01 11:41:57 浏览次数:20
深圳设计网页公司
以下实例使用嵌套 for 循环来输出菱形:
#include <iostream>
#include <math.h>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
//外层循环控制行、换行
//内层循环控制列、列的图形
//中分的三角菱形
//定义半菱形高度,即定义了菱形的大小
int n ;
cout<<"请输入半菱形高度"<<endl;
cin >> n;
//上半部分居中正三角n行
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - i -1; j++)
{
cout<<" ";
}
for (int j = 0; j <= 2 * i; j++)
{
//每行第一个和最后一个外打印星号,其余打印空格,做成空心效果,下半部分相同
if (j == 0 or j == 2 * i)
cout<<"*";
else
cout<<" ";
}
cout<<endl;
}
//下半部分居中倒三角n-1行
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j <= i; j++)
{
cout<<" ";
}
for (int j = 0; j <= 2 * ( n - i - 2 ); j++)
{
if (j == 0 or j == 2 * ( n - i - 2 ))
cout<<"*";
else
cout<<" ";
}
cout<<endl;
}
return 0;
}
测试输出结果:
请输入半菱形高度
5
*
* *
* *
* *
* *
* *
* *
* *
*
我说两句
我说两句
104***3768@QQ.com
4年前 (2018-10-01)
adults
223***32@qq.com
36
利用循环输出乘法口诀:
#include<iostream>
#include <iomanip>
using namespace std;
int main()
{
int i, j;
for (i = 1; i < 10; i++){
for (j = 1; j <= i; j++){
cout << j << " × " << i << " = " << setw(2)<<i *j << " ";
}
cout << endl<<endl;
}
}
adults
adults
223***32@qq.com
4年前 (2018-11-01)
lxcyha
lxc***@gmail.com
164
楼上的输出菱形方法太麻烦了,请直接来这个:
#include <iostream>
#include <math.h>
using namespace std;
int main() {
cout << "请输入半菱形高度n" << endl;
int n = 0;
cin >> n;
for (int i = 0; i < 2 * n + 1; i++) {
for (int j = 0; j < 2 * n + 1; j++) {
if (abs(i - n) + abs(j - n) == n) {
cout << "*";
} else {
cout << " ";
}
}
cout << endl;
}
}
lxcyha
lxcyha
lxc***@gmail.com
4年前 (2019-01-07)
疯人轻语
lpt***210646@qq.com
42
楼上的方法让我眼前一亮(本人大一的小白),忍不住研究了一下,觉得这样子写虽然很棒,但是不符合题意了,稍微修改了一下。
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
cout << "请输入半菱形高度n" << endl;
int n = 0;
cin >> n;
for (int i = 0; i < 2 * n; i++)
{
for (int j = 0; j < 2 * n; j++)
{
if (abs(i - n) + abs(j - n) == n - 1) //输出星号时满足的规律
{
cout << "*";
}
else
{
cout << " ";
}
}
cout << endl;
}
return 0;
}
疯人轻语
疯人轻语
lpt***210646@qq.com
3年前 (2019-10-26)
嗯、行家啊
112***7739@qq.com
21
楼上的方法虽然更简便,但是会多输出空白的行和列,所以我在楼上的代码上稍作修改,现在的代码我觉得更符合题意。
#include<iostream>
using namespace std;
//利用for循环输出菱形
int main()
{
cout << "请输入半菱形高度n" << endl;
int n = 0;
cin >> n;
for (int i = 1; i < 2 * n; i++)
{
for (int j = 1; j < 2 * n; j++)
{
if (abs(i - n) + abs(j - n) == n - 1) //输出星号时满足的规律
{
cout << "*";
}
else
{
cout << " ";
}
备案号: 苏ICP备11067224号
CopyRight © 2011 书生商友信息科技 All Right Reserved
24小时服务热线:品茶服务联系十Q/Q:【3775586952】 E-MAIL:1120768800@qq.com QQ:1120768800
网址: https://www.768800.com 网站建设:上往建站
关键词: 网站建设| 域名邮箱| 服务器空间| 网站推广| 上往建站| 网站制作| 网站设计| 域名注册| 网络营销| 网站维护|
企业邮箱| 虚拟主机| 网络建站| 网站服务| 网页设计| 网店美工设计| 网站定制| 企业建站| 网站设计制作| 网页制作公司|
400电话办理| 书生商友软件| 葬花网| 调温纤维| 海洋馆运营维护| 北京保安公司| 殡仪馆服务| 殡葬服务| 昌平殡葬| 朝阳殡葬|
欢迎您免费咨询,请填写以下信息,我们收到后会尽快与您联系
服务热线:品茶服务联系十Q/Q:【3775586952】