对于赋值,我需要编写一个程序,该程序接受用户输入的字符串,并使用给定字符串的字母输出菱形图案。(不使用数组)。
例如:
> 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;
}这是一个由星号组成的三角形。一开始,我认为我可以编辑一些变量,并使用源代码来处理间距,但很明显,因为我真的不明白变量最初是如何影响问题的,所以我没有做多大的工作。如果有人能向我解释我该如何处理这个问题,我将不胜感激。
发布于 2020-02-20 19:52:18
处理这些问题的一个很好的方法是从一张图片开始,比如你在问题中链接到的图片。现在,对于五个字母的单词"Hello",您可以从图片中看出H位于位置4。(请记住,数组和字符串索引从0开始。)下一步还将查看其他示例。例如,让我们来看看钻石对三个字母的单词"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前导空间之间有三个空格。你开始看到一个模式了吗?看看第一个例子的第四行和第五行("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仍然是一个特例,因为您只打印了一次。
https://stackoverflow.com/questions/60327196
复制相似问题