如何解决如何在 C++ 中去除三角形之间的间距?
最近,我写了一个形状生成器,用 C++ 生成三角形和矩形。在这个程序中,矩形函数工作正常,因为它在“O”之间没有间距。但是,对于我的三角形函数,'O'之间有一个间距,无论我如何调整,'O'之间的间距都无法消除。例如,当用户输入 5 作为三角形的高度时,就会出现间隙。这是我屏幕上显示的输出:
O
O O
O O O
O O O O
O O O O O
我希望产生如下所示的输出:
是否有解决此问题的解决方案或建议?谢谢你的建议。
这是我的代码:
#include <iostream>
#include <fstream>
#include <conio.h>
using namespace std;
void printTriangle()
{
cout << "Enter height of triangle : ";
int n;
cin >> n;
int k = 2 * n - 2;
cout << "\n\n";
// open a file in write mode.
ofstream outfile;
outfile.open("shape_generator.txt");
// character to be printed
char ch = 'O';
// outer loop to handle number of rows
// n in this case
for (int i = 0; i < n; i++) {
// inner loop to handle number spaces
// values changing acc. to requirement
for (int j = 0; j < k; j++){
cout << " ";
outfile << " ";
}
// decrementing k after each loop
k = k - 1;
// inner loop to handle number of columns
// values changing acc. to outer loop
for (int j = 0; j <= i; j++) {
// printing stars
cout << ch << " ";
outfile << ch << " ";
}
// ending line after each row
cout << endl;
outfile << "\n";
}
cout << "\n\n\n";
}
void printRectAngle(){
int i,j,N,M;
/* Input number of rows from user */
cout << "Enter Height: ";
cin >> N;
cout << "Enter Width: ";
cin >> M;
cout << "\n\n\n";
// open a file in write mode.
ofstream outfile;
outfile.open("shape_generator.txt");
/* Iterate through N rows */
for(i=1; i<=N; i++)
{
/* Iterate over columns */
for(j=1; j<=M; j++)
{
/* Print star for each column */
cout << "O";
outfile << "O";
}
/* Move to the next line/row */
cout << "\n";
outfile << "\n";
}
cout << "\n\n\n";
// close the opened file.
outfile.close();
}
int main()
{
int option;
do
{
cout << "Welcome to Shape Generator Service!\n\n";
cout << "1.Triangle" << endl;
cout << "2.Rectangle" << endl;
cout << "0.Exit" << endl;
cout << "Enter option : ";
if(cin >> option)
{
switch (option)
{
case 1:
system("cls");
printTriangle();
break;
case 2:
system("cls");
printRectAngle();
break;
case 0:
break;
default:
cout << "The Option is Not Available." << endl;
break;
}
}
else
{
cout<<"Only Digits are Allowed! Press any key to continue..." << endl;
getch();
cin.clear();
cin.ignore();
option = 15;
}
}while(option != 0);
}
解决方法
这里有一些可能有效的方法,具体取决于您的终端功能。
由于您的图片显示了每隔一行的半步,您可能可以使用 unicode U+2009 字符 Thin Space 来缩进每隔一行多一点。
#include <iostream>
int main() {
auto thinspace = "\u2009";
std::cout
<< " O\n"
<< thinspace << " OO\n"
<< " OOO\n"
<< thinspace << "OOOO\n"
<< "OOOOO\n"
;
}
注意:这在我自己的终端窗口中不起作用,但显然它适用于 Godbolt - 所以如果这足够好取决于您计划在哪里显示结果。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。