用C ++打印模式 [英] Printing a pattern in C++
问题描述
模式如下:
1. _ _ _ *
2. _ _ * *
3. _ * * *
4. * * * *
[忽略数字:只是用它们来增加可读性,和下划线是这里的空间用于表示。]
很好用2 for或while循环很容易做到这一点,但我的朋友只用一个循环挑战我。我必须为它创建一个通用程序,这样它不仅可以运行4个,也可以运行5个或6个。
我试过试过,直到现在我已达到这个目的:
The pattern is as follows:
1. _ _ _ *
2. _ _ * *
3. _ * * *
4. * * * *
[Ignore numbers: just used them to increase readiblity, and underscores are spaces here for representation.]
Well its quiet easy to do it with 2 for or while loops , but my friend challenged me to it with only 1 loop.And i have to create a general program for it , so that it runs for not only 4 but 5 or 6 too.
Well i tried and tried , and till now i have reached this far:
int a=1;
int times=4; // no. of times a line , 4 here but user can enter anything
int totalelements=times*times;
int n=1;
int breakpoint=(times*n)-(n-1);
// breakpoints are the first occurences of * like 4th position in 1st line, 7th in 2nd line..
while(a<(totalelements+1))
{
if (breakpoint==a)
{cout<<"*";
n++; //to increment n for next value in breakpoint formula
breakpoint=(times*n)-(n-1); } //get new breakpoint formula
else cout<<" ";
if(a%times==0) { cout<<endl;} // for printing nextline every 4th element here
}
预期产量为:
1. _ _ _ *
2. _ _ * _
3. _ * _ _
4. * _ _ _
所以我做错的事情是:我能够找到它的断点模式,但它只在那些断点打印星星,而不是在那之后。 />
我应该怎么做,在那个断点之后打印那些星星
我能说的一件事就是不行。正在打印的星星是当时n的值,所以我应该如何链接它?
程序必须只使用1个循环,否则不能。变量,没有goto语句。
The expected output is :
1. _ _ _ *
2. _ _ * _
3. _ * _ _
4. * _ _ _
So the thing i am doing wrong is : i am able to find out breakpoint pattern for it , but it prints stars only at those breakpoints , not after that.
How should i do that , to print those stars after that breakpoint
one thing i can relate is the no. of stars being printed is the value of n at that time, so how should i link it?
The program must use only 1 loop , any no. of variables , and no goto statement .
推荐答案
我认为你可以简化问题,只需要识别所需模式的二维性质,即你有行 列:
I think you may simplify the matter just recognizing the bidimensional nature of the required pattern, that is you have rows an columns:
#include <iostream>
using namespace std;
int main()
{
int n=4; // no. of times a line , 4 here but user can enter (almost :-) ) anything
for (int i=0; i<n*n; ++i)
{
int r = i/n; // row number
int c = i%n; // column number
cout << (c < n-1-r ? ' ':'*');
if (c==n-1) cout << endl;
}
}
这篇关于用C ++打印模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!