
在C++中,我們可以使用setprecision(n)
函數來控制輸出結果的小數位數。這個函數定義在<iomanip>
頭文件中,它可以與fixed
函數一起使用,以確保小數點后的位數固定。以下是一些常見的用法示例:
1. 使用setprecision(n)
和fixed
函數
using namespace std;
int main() {
double num = 3.1415926;
cout << fixed << setprecision(2) << num << endl; // 輸出: 3.14
return 0;
}
2. 不使用fixed
函數
using namespace std;
int main() {
double num = 3.1415926;
cout << setprecision(2) << num << endl; // 輸出: 3.1
return 0;
}
3. 使用printf
函數(C風格)
int main() {
float num = 3.1415926;
printf("%.2f\n", num); // 輸出: 3.14
return 0;
}
4. 使用stringstream
類
using namespace std;
int main() {
double num = 3.1415926;
stringstream ss;
ss << fixed << setprecision(2) << num;
cout << ss.str() << endl; // 輸出: 3.14
return 0;
}
5. 手動計算
using namespace std;
int main() {
double num = 3.1415926;
int precision = 2;
num = round(num * pow(10, precision)) / pow(10, precision);
cout << num << endl; // 輸出: 3.14
return 0;
}
以上代碼示例展示了在C++中保留輸出結果小數的不同方法。根據具體需求,可以選擇合適的方法來控制輸出的小數位數。