C++实现浮点数输出时小数点后补两位零的问题求解
解决方案
你代码已经引入了格式控制所需的<iomanip>头文件,只需在文件写入逻辑前给outFile输出流设置2个格式参数即可:
- 启用
fixed标记:强制使用固定小数位格式输出浮点数,关闭默认自动省略末尾小数零的逻辑 - 搭配
setprecision(2):指定固定小数位保留2位,不足位自动补零
修改步骤
在outFile.open("outData.txt");执行完成后、第一次向outFile写入内容前,添加如下代码即可:
outFile << fixed << setprecision(2);
该格式设置会对后续所有流向outFile的浮点数值输出生效,无需为每个输出单独配置。
修改后完整代码
#include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; int main() { ifstream inFile; ofstream outFile; string firstName, lastName, department; double salary, bonus, taxes; double distance, timeTravel; int coffeeCups; double cupCost; double paycheck, aveSpeed, salesAmount; inFile.open("inData.txt"); outFile.open("outData.txt"); // 新增格式控制代码 outFile << fixed << setprecision(2); inFile >> firstName >> lastName >> department; inFile >> salary >> bonus >> taxes; inFile >> distance >> timeTravel; inFile >> coffeeCups >> cupCost; paycheck = salary + salary*(bonus/100) - ((salary+ salary*(bonus/100))*(taxes/100)); aveSpeed = distance/timeTravel; salesAmount = coffeeCups * cupCost; outFile << "Name: " << firstName << " " << lastName << ", Department: " << department << endl; outFile << "Monthly Gross Salary: $" << salary << ", Monthly Bonus: " << bonus << "%" << ", Taxes: " << taxes << "%" << endl; outFile << "Paycheck: $" << paycheck << endl << endl; outFile << "Distance Traveled: " << distance << " miles, Traveling Time: " << timeTravel << " hours" << endl; outFile << "Average Speed: " << aveSpeed << " miles per hour" << endl << endl; outFile << "Number of Coffee Cups Sold: " << coffeeCups << ", Cost: $" << cupCost << " per cup" << endl; outFile << "Sales Amount = $" << salesAmount; inFile.close(); outFile.close(); return 0; }
修改后输出的所有浮点数值都会自动保留两位小数,不足位补零,完全符合预期输出要求。
内容的提问来源于stack exchange,提问作者hannahcrow
相关产品推荐
相关产品推荐

