問題
如何在數字之間留出空格?當我在模式改變<<" "后添加一個cout<<j。有沒有其他方法可以在數字之間留出空格?
代碼
#include<iostream>
using namespace std;
int main(){
int i,j=1,space,star,n;
cin>>n;
i=1;
回圈
while(i<=n){
space=n-i;
while(space){
cout<<" ";
space--;
}
star=i;
while(star){
cout<<j<<" ";
j ;
star--;
}
cout<<"\n";
i ;
}
return 0;
}
n=4 的輸出
1
23
456
78910
我想要這個輸出:-
1
2 3
3 4 5
7 8 9 10
uj5u.com熱心網友回復:
對于預期的輸出,您只需要在while(space)回圈中添加第二個空格:
space = n - i;
while (space) {
std::cout << " "; // note: two spaces
space--;
}
或乘space由2之前的回圈:
space = 2 * (n - i);
while (space) {
std::cout << ' ';
space--;
}
你也可以#include <string>跳過回圈:
space = 2 * (n - i);
std::cout << std::string(space, ' ');
跳過回圈的另一種方法是#include <iomanip>使用std::setw.
請注意,您也可以使用std::setw和std::left來更正while (star)回圈,以使該模式最多保持n = 13.
space = 2 * (n - i) 1;
std::cout << std::setw(space) << "";
while (star) {
std::cout << std::setw(2) << std::left << j;
j ;
star--;
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/365024.html
