浮点数被C ++舍入到小数点后一位

问题描述

我正在编写一个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进行编码

解决方法

此链接可能会帮助[link] [1]

float iBalance = getBalance(); 

std::cout<< std::setprecision(2)<<iBalance<< endl; 

[1]:https://stackoverflow.com/questions/5907031/printing-the-correct-number-of-decimal-points-with-cout#:~:text=You%20have%20to%20set%20the%20'float%20mode'%20to%20fixed.&text=To%20set%20fixed%202%20digits,ios%3A%3Afixed)%3B%20cout。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...