Hàm setw() trong C++ dùng. Thư viện iomanip cung cấp hàm setw() để thay đổi độ rộng của bề rộng khi dữ liệu xuất ra.
Ví dụ 1:
int x = 13;
cout<<x<<endl;
ví dụ 2:
Ta dùng hàm setw():
int x = 13;
cout<<setw(10)<<x<<endl;
Ví dụ 3:
#include<iomanip>
#include<iostream>
#include<math.h>
using namespace std;
int main(){
#include<iomanip>
#include<iostream>
#include<math.h>
using namespace std;int main(){
//set the number you want to square and cube to.
int x = 50;
//set the width
int w = 10;
//output the column headings
//use setw() with a arg for the width
cout<<setw(w)<<“Number”<<setw(w)<<“Square”<<setw(w)<<“Cube”<<endl;
cout<<“====================================”<<endl;
//loop through
for(int i = 3; i<=x; i+=9)
{
//output the number, square and cube in fields of width x
cout<<setw(w)<<i<<setw(w)<<pow(i,2)<<setw(w)<<pow(i,3)<<endl;
}
}
#include<iostream>
#include<math.h>
using namespace std;int main(){
//set the number you want to square and cube to.
int x = 50;
//set the width
int w = 10;
//output the column headings
//use setw() with a arg for the width
cout<<setw(w)<<“Number”<<setw(w)<<“Square”<<setw(w)<<“Cube”<<endl;
cout<<“====================================”<<endl;
//loop through
for(int i = 3; i<=x; i+=9)
{
//output the number, square and cube in fields of width x
cout<<setw(w)<<i<<setw(w)<<pow(i,2)<<setw(w)<<pow(i,3)<<endl;
}
}
Khi chạy ta có kết quả sau:

Lượt xem (37915)