浮点数被 C++ 四舍五入到小数点后一位
floats getting rounded to 1 decimal by C++
我正在编写一个 C++ 程序,它接受用户输入并将其放入一个文件中。在这种情况下,它接受一个数字(例如 299.99),但是当使用双精度和浮点数 299.9...
时,C++ 将其四舍五入为 300(以前是双精度)
我的代码:
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() 方法时,它也是 returns 一个浮点数,但正如我所说,只有一位小数...
这是文本文件中的一个片段:
[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 可能会有所帮助 [link][1]
float iBalance = getBalance();
std::cout<< std::setprecision(2)<<iBalance<< endl;
[1]: )%3B%20cout.
我正在编写一个 C++ 程序,它接受用户输入并将其放入一个文件中。在这种情况下,它接受一个数字(例如 299.99),但是当使用双精度和浮点数 299.9...
时,C++ 将其四舍五入为 300(以前是双精度)我的代码:
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() 方法时,它也是 returns 一个浮点数,但正如我所说,只有一位小数...
这是文本文件中的一个片段:
[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 可能会有所帮助 [link][1]
float iBalance = getBalance();
std::cout<< std::setprecision(2)<<iBalance<< endl;
[1]: )%3B%20cout.