我正在编写一个C ++程序,该程序需要用户输入并将其放入文件中。在这种情况下,它接受一个数字(例如299.99),但是C ++在使用双精度数时将其四舍五入为300(以前是双精度数)并将其浮点数299.9 ...
我的代码:
void Bank::deposit(){
std::cout << "You currently have " << getBalance() << " in your account.\nHow much would you like to deposit? Amount: ";
float amount = optionExists(amount);
if(amount < 1){
std::cout << "Invalid Amount!" << std::endl;
deposit();
}
float moneyInBank = getBalance();
setBalance(moneyInBank + amount);
std::cout << "Your balance of " << moneyInBank << " has been increased to " << getBalance() << std::endl;
std::string theLine = getUsername() + "," + getPassword() + "," + getAccountType() + "," + std::to_string(moneyInBank) + "," + std::to_string(getAdmin());
updateFile(theLine, getUsername(), getPassword(), getAccountType(), getBalance(), (getAdmin()));
displayMenu();
}
当我调用getBalance()方法时,它还会返回一个浮点数,但是正如我所说的,只能返回一个小数点...
这是文本文件中的摘录:
[name,password,type,BALANCE,admin]
lisa,mag24@773,C,24.99,0 ---> What I want (manually entered)
lols,23456,L,30,1 ---> What I got when using doubles
mark,passw0rd,S,24509.9,1 ---> What I got when using floats
附加说明:我使用cmake进行编译,并使用VSCode进行编码
答案 0 :(得分:0)
此链接可能会帮助[link] [1]
float iBalance = getBalance();
std::cout<< std::setprecision(2)<<iBalance<< endl;