* 三角形... [英] * triangle...
问题描述
大家好,
使用某些循环,可以很容易地在屏幕上打印下面给出的由*制成的钻石.
*
***
*****
*******
*****
***
*
但是我有一个朋友问我一个问题,他说只用一个循环就可以印出相同的钻石.
我已经尝试了多种方法,例如复杂的逻辑和if-else条件,但无法通过单循环打印准确的形状,而且我的好奇心:doh:也增加了以了解解决方案.
有人能帮我做一个逻辑(方程式)来打印可能1圈的钻石吗?
谢谢
vikas
Hi all,
A diamond made of * given below can be easily printed on the screen using some loops.
*
***
*****
*******
*****
***
*
But i have got a question from one of my friend says print the same * diamond using only one loop.
I have tried with many ways such as complex logic and if-else condition but could not print exact shape with single loop and my curiosity :doh: is also increased to know the solution.
can anybody help me with a logic (equation) that can print the diamond with possible 1 loop.
Thanks
vikas
推荐答案
您可以解决以下代码段:
You can work around the code snippet below:
char szSpaces[] = " ";
char szStars[] = "*****************************************";
int iSpaces = 5;
int iStars = 7;
printf("%.*s%.*s\n", iSpaces, szSpaces, iStars, szStars);
这样的格式字符串指示printf
函数打印szSpaces
字符串的前iSpaces
个字符,然后打印szStars
字符串的前iStars
个字符. >
请注意,如果所需字符数大于字符串长度,则完整字符串将被打印而没有任何填充.
您可以通过一个简单的循环来编写函数,在每个循环中,您需要在每个步骤上计算要打印的正确数量的空格和星号.
Such a format string instruct the printf
function to print the first iSpaces
characters of the szSpaces
string, followed by the first iStars
characters of the szStars
string.
Note that if the number of required characters is greater than the string length, the full string is printed without any padding.
You can write your function with a simple loop, where on each step you compute the right number of spaces and asterisks to print.
您已经编写了哪些代码?
看到我可能可以很快将您指向正确的方向.
What code have you written already?
On seeing that I can probably point you in the right direction quite quickly.
从技术上讲,您可以在没有任何循环的情况下进行打印.您考虑使用两个循环执行的操作,并在没有内部循环的情况下重新组织逻辑.
抱歉,由于缺乏代码,我无法再提供更多信息,因此有可能这实际上只是变相的作业.
You could technically print it without any loops what so ever. You think about what you''re doing with two loops and reorganize the logic without the inner loop.
Sorry, I cannot give you more based on the lack of code and the chance that this is really just homework in disguise.
这篇关于* 三角形...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!