[英]How should I modify this code to print a diamond pattern using the letters from a given string?
对于作业,我需要编写一个程序,该程序接受用户输入的字符串并使用给定字符串的字母输出菱形图案。 (不使用数组)。
例如:
> Enter a word: hello
h
e e
l l
l l
o o
l l
l l
e e
h
我一直在理解如何为这些事情操作嵌套的 for 循环时遇到问题,所以我尝试获取类似问题的源代码并对其进行修改。
#include <iostream>
using namespace std;
int main()
{
int n,k,c,space=1;
cout<<"Enter the number of Rows..."<<endl;
cin>>n;
space=n-1;
for(k=1;k<=n;k++)
{
for(c=1;c<=space;c++)
{
cout<<" ";
}
space--;
for(c=1;c<=2*k-1;c++)
{
cout<<"*";
}
cout<<endl;
}
space=1;
for(k=1;k<=n;k++)
{
for(c=1;c<=space;c++)
{
cout<<" ";
}
space++;
for(c=1;c<=2*(n-k)-1;c++)
{
cout<<"*";
}
cout<<endl;
}
return 0;
}
这将打印一个由星号组成的三角形。 最初我以为我可以稍微编辑一下变量并使用源代码为我处理间距,但显然因为我真的不明白变量如何影响问题,所以我还没有走多远. 如果有人能向我解释我应该如何解决这个问题,我将不胜感激。
处理此类问题的一个好方法是从一张图片开始,例如您在问题中链接的图片。 现在,对于五个字母的单词“Hello”,您可以从图中看出 H 以位置 4 为中心。(记住,数组和字符串索引从 0 开始。)下一步也是查看其他示例。 例如,让我们看看钻石对于 3 个字母的单词“cat”的含义。
c
a a
t t
a a
c
这一次,字母“c”位于位置 2 的中心。做这些例子的目的是找到一个模式; 在这里,我们发现模式是第一个字母始终以word length - 1
位置为中心。 因此,在第一个字母的行中有word length - 2
前导空格。
下一行呢? 请注意如何在重复字母之间少一个前导空格和一个额外空格。 因此,我们有word length - 2 - 1
前导空格和1
空格分隔它们。
第三行呢? 现在我们在字母和word length - 2 - 2
之间有三个空格word length - 2 - 2
前导空格。 你开始看到一种模式了吗? 查看第一个示例(“Hello”)的第四和第五行并尝试找出前导空格和字母之间的空格数如何。 一旦你试过了,请阅读下面的内容。
每次我们向下一排,我们都会失去一个领先的空间。 除了第二行,每次我们向下一行,我们也会在字母之间获得两个空格。 现在,你能把这个模式转换成公式吗? 再次,看看你是否能想出一个公式,然后继续阅读。
我们已经了解到,前导空格的数量等于word length - 1 - row
(其中row
从 0 开始),字母之间的空格数等于row * 2 - 1
。 (注意这个公式如何正确处理第二行的情况。)
因此,您的代码应如下所示:
// Word of caution: I have not tested this code.
using namespace std; // Bad practice in production code; used here for simplicity.
// *snip*
string my_word;
cin >> my_word;
int middle_index = my_word.length() - 1;
for (int r = 0; r < my_word.length; ++r) {
// This code prints the top part of the diamond.
for (int ls = 0; ls < middle_index - r; ++ls) {
cout << " "; // Print out the leading spaces.
}
cout << my_word[r]; // You can replace this with my_word.substr(r, 1)
// if you are unallowed to treat strings like arrays.
// r == 0 is a special case since we only print one of those letters.
if (r == 0) {
continue;
}
// Otherwise, we simply need to print the number of spaces in-between.
for (int bs = 0; bs < 2 * r - 1; ++bs) {
cout << " ";
}
cout << my_word[r];
}
现在要打印钻石的另一半,您必须执行与上述类似的操作。 请记住以word length - 2
开始循环(请参阅您的图片以了解原因)并每次减少循环索引。 另外不要忘记r == 0
仍然是一种特殊情况,因为您只打印一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.