如何使用C ++中的嵌套循环打印以下模式 [英] How do I print the following pattern using nested loops in C++

查看:102
本文介绍了如何使用C ++中的嵌套循环打印以下模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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





我尝试过:



i尝试了几个for循环,但仍然无法解决..



What I have tried:

i have tried several for loops but still couldn't make out..

推荐答案

这很简单。但是......这是你的功课,所以没有代码! :笑:

看看模式,很明显你需要至少两个循环:

1)打开每一行的外循环。

2)内部循环打印每行的内容。



外循环很简单:for循环只运行行数。从零开始,大于4时结束。

内循环是一项工作,但不是很多。

在每种情况下,你想要打印(行号* 2)中间的空格。每一端的星数是(10 - 空格数)/ 2

所以你的内码将是三个循环:一个用于在开始时打印星星,然后一个用于空格,然后最后一个用于星星。

简单!



你可以通过允许行数变量来使这更通用,以及每行打印的总字符数(在您的示例中为10)是行数的两倍。所有的数学都是一样的!



试一试:如果你想几分钟的话,它真的不复杂!
It's pretty simple. But... this is your homework, so no code! :laugh:
Look at the pattern, and it pretty obvious that you will need at least two loops:
1) Outer loop to print each line.
2) Inner loop(s) to print the content of each line.

Outer loop is simple: a for loop just running for the number of lines. Start at zero, end when greater than 4.
Inner loop(s) is a little more work, but not a lot.
In each case, you want to print (line number * 2) spaces in the middle. The number of stars at each end is (10 - number of spaces) / 2
So your inner code will be three loops: one to print the stars at the start, then one for the spaces, then one for the stars at the end.
Easy!

You can make this more generic by allowing the number of lines to be a variable, and the "total characters to print per line" (10 in your example) to be twice the number of lines. All the math is the same!

Give it a try: it's really not complicated at all if you think about it for a couple of minutes!


非常简单,但它是HomeWork,我们不会根据要求提供完整的爆炸解决方案。

如果您需要帮助,请显示您的代码并说明具体问题代码。



否则,你需要分析问题。

拿一张纸,注意你要做什么来手动编写。
每行
,记下你需要做什么。

将你需要在每一行上做的与行号相关联,你应该拿出来你需要编程的东西非常接近。
Pretty simple, but it is HomeWork, and we don't provide full blowup solutions just on request.
So show your code and state a specific problem if you want help on your code.

Otherwise, you need to analyze the problem.
Take a sheet of paper, note what you would do to write it manually.
for each line, note what you need to do.
make the relation between what you need to do on each line with the line number, you should come up with something pretty close what you need to program.


这是我的例子。当列= 2 *行时,你想要的效果可以实现。

希望这个例子会让你开心。



Here is my example.when column = 2*row,the effet you want can be realized.
Hope this example will make you happy.

#include<iostream>

int main()
{
	const int column = 10;
	const int row = 5;
	for(int i = 0; i < row; ++i)
	{
		for(int j= 0; j < column; ++j)
		{
			if( j == ((column/2) - i))
				for(int k= 0 ; k < (2*i) ; ++k)
				{
					std::cout << ' ';
					++j;
				}
			std::cout << '*';
		}
		std::cout << std::endl;
	}
	return 0;
}


这篇关于如何使用C ++中的嵌套循环打印以下模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆