背景和问题:
我已经为课堂创建了菱形形状程序,但是对于均匀的菱形行,我遇到了问题。我在想我的逻辑可能有问题。似乎每当我使用偶数行作为菱形时,它就不会显示为偶数行而是奇数行。
我尝试了其他可能的“解决方案”,但是它们没有起作用。
例如,我将for (int b = 0; b < asterisk; b++)
更改为(int b = 0; b <= asterisk; b++)
,它显示了正确的行数,但是不再是适当的菱形形状。它也(显然)影响了奇数行钻石,因此它们看起来也不像合适的钻石。
我完全被困住了,绝对希望朝着正确的方向前进。
这是我的代码:
#include <iostream>
using namespace std;
int main() {
int i, j, space, asterisk;
do
{
cout << "Enter the number of rows desired to make a diamond pattern (0 to quit): ";
cin >> i;
j = (i - 1) / 2;
for (int z = 0; z < i; z++)
{
space = abs(j - z);
asterisk = i - 2 * space;
for (int a = 0; a < space; a++)
cout << " ";
for (int b = 0; b < asterisk; b++)
cout << "*";
for (int c = 0; c < space; c++)
cout << " ";
cout << endl;
}
} while (i > 0);
cout << "Goodbye!" << endl;
}
非常感谢你!
最佳答案
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
int i, j, space, asterisk, is_even;
do
{
cout << "Enter the number of rows desired to make a diamond pattern (0 to quit): ";
cin >> i;
is_even = (i % 2 == 0) ? 1 : 0;
//Above line uses ternary operator to assign is_even flag to 1 if the number is even and 0 if it is not.
j = (i - 1) / 2;
for (int z = 0; z < i; z++)
{
space = abs(j - z);
asterisk = (is_even) ? i - 2 * space - 1 : i - 2 * space; //Change 1
for (int a = 0; a < space; a++)
cout << " ";
//Change 2.STARTS
if(space == 0 && is_even ){
for (int b = 0; b < asterisk; b++)
cout << "*";
cout<<endl;
}
//Change 2.ENDS
for (int b = 0; b < asterisk; b++)
cout << "*";
//for (int c = 0; c < space; c++)
// cout << " ";
//You dont need to add the spaces at the end of each line.
cout << endl;
}
} while (i > 0);
cout << "Goodbye!" << endl;
}
输出::
Enter the number of rows desired to make a diamond pattern (0 to quit): 1
*
Enter the number of rows desired to make a diamond pattern (0 to quit): 2
*
*
Enter the number of rows desired to make a diamond pattern (0 to quit): 3
*
***
*
Enter the number of rows desired to make a diamond pattern (0 to quit): 4
*
***
***
*
Enter the number of rows desired to make a diamond pattern (0 to quit): 5
*
***
*****
***
*
Enter the number of rows desired to make a diamond pattern (0 to quit): 6
*
***
*****
*****
***
*
Enter the number of rows desired to make a diamond pattern (0 to quit): 7
*
***
*****
*******
*****
***
*
Enter the number of rows desired to make a diamond pattern (0 to quit): 8
*
***
*****
*******
*******
*****
***
*
Enter the number of rows desired to make a diamond pattern (0 to quit): 0
Goodbye!