在C++中,你可以使用iostream
庫中的std::cout
對象來自定義輸出格式。這里有一些常用的方法來實現自定義輸出格式:
std::setw
設置字段寬度:#include <iostream>
#include <iomanip>
int main() {
int value = 42;
std::cout << std::setw(5) << value << std::endl; // 輸出寬度為5的整數
return 0;
}
std::setprecision
設置浮點數精度:#include <iostream>
#include <iomanip>
int main() {
double value = 3.14159265358979323846;
std::cout << std::setprecision(5) << value << std::endl; // 輸出保留5位小數的浮點數
return 0;
}
std::left
、std::right
和std::internal
設置對齊方式:#include <iostream>
#include <iomanip>
int main() {
int value = 42;
std::cout << std::left << std::setw(5) << value << std::endl; // 左對齊,寬度為5
std::cout << std::right << std::setw(5) << value << std::endl; // 右對齊,寬度為5
std::cout << std::internal << std::setw(5) << value << std::endl; // 內對齊,寬度為5
return 0;
}
std::fixed
和std::scientific
設置浮點數表示法:#include <iostream>
#include <iomanip>
int main() {
double value = 3.14159265358979323846;
std::cout << std::fixed << std::setprecision(5) << value << std::endl; // 輸出保留5位小數的浮點數,使用固定表示法
std::cout << std::scientific << std::setprecision(5) << value << std::endl; // 輸出保留5位小數的浮點數,使用科學計數法表示法
return 0;
}
你可以根據需要組合使用這些方法來自定義輸出格式。例如:
#include <iostream>
#include <iomanip>
int main() {
int value = 42;
double pi = 3.14159265358979323846;
std::cout << std::left << std::setw(5) << value << std::endl;
std::cout << std::right << std::setw(5) << pi << std::endl;
std::cout << std::fixed << std::setprecision(5) << pi << std::endl;
return 0;
}
這將輸出:
42
3.14159
3.14159