簡體   English   中英

如何使 output 的嵌套在 C++ 的右側對齊?

[英]How can I make my nested for output align on right in C++?

我剛剛學習嵌套 for,我的任務之一是讓我的 output 右對齊,但我不太明白我該怎么做

我的代碼:

#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
    int x,y;

    for (y=1; y<=5; y++)
    {
        for (x=y; x<=5; x++)
        {
            cout<<"*";
        }
        cout<<endl;
    }
    getch();
}

Output:圖片

我想做的:圖片

這很好用。 確保先打印空格,然后再打印 *。 隨着行號的增加,空間增加 1,* 減少 1。

#include <stdio.h>

int main()
{
    int rows=5,i,j,space;
    for (i = rows; i >= 1; --i) {
      for (space = 0; space < rows - i; ++space)
         printf("  ");
      for (j = i; j <= 2 * i - 1; ++j)
         printf("* ");
      printf("\n");
}

    return 0;
}

按照我如何提問和回答家庭作業問題?
我提供一個提示:
始終打印全行長度並確保您事先打印足夠的" "
或使用您選擇的 output 方法的特殊格式功能自動執行縮進/對齊。

對於顯式打印" " ,您可以決定每個字符是打印" "還是"*"
或者您可以在第一個內部循環中打印足夠的" " ,然后在第二個內部循環中打印"*" ,如您顯示的代碼所示。

要右對齊,您需要在星號之前打印一些空白字符。 這在std::string構造函數的幫助下很容易執行

#include <iostream>
#include <string>

//#include <conio.h>
//using namespace std;

int main()
{
    int n = 5;
    for (int y = 1; y <= n; y++)
    {
        std::cout << std::string(y-1, ' ') << std::string(n-y+1, '*') << std::endl;
    }
    //getch();
}

不確定您要使用 C function 但這有效。 完成此任務的一種可能方法是在要打印的字符前面添加填充。 對於 printf,在格式字符串中使用“*”將告訴 printf 從 arguments 中獲取值。因此,

printf("%*s", y, " ");

s 將由字符 " " 填充,填充將由 y 填充,你循環計數器。

#include <cstdio>


int main()
{
    int x,y;

    for (y=1; y<=5; y++)
    {
        for (x=y; x<=5; x++)
        {
            printf("%s", "*");
        }
        printf("\n");
        printf("%*s", y , " ");
    }
}

要在寬度為 5 的線上右對齊,您可以使用std::right (在 iostream 中)和std::setw (在 iomanip 中),如下所示:

#include <iostream>
#include <iomanip>
#include <sstream>
    
using namespace std;

int main()
{
    
    int x,y;
    
    for (y=1; y<=5; y++)
    {
        stringstream buf1;
        for (x=y; x<=5; x++)
        {
            buf1 << "*";
        }
        cout << right << setw(5) << buf1.str() << endl;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM