【发布时间】:2022-01-09 08:29:36
【问题描述】:
所以我正在用 C++ 制作一个基本的银行程序,并有一个接受双精度的存款函数,所以我想处理来自用户的输入,该双精度作为货币有效,因此保留 2 个小数位且不少于0.
解决此问题的最佳方法是什么? 到目前为止我有这个,还有什么我需要检查货币验证或可以用更少的代码行完成的任何事情吗?谢谢
// allow user to deposit funds into an account
try{
double amount = std::stoi(userInput); // userInput is a string
if (amount < 0)
{
throw std::invalid_argument("Amount cannot be negative");
}
// call function to deposit
std::cout << "You have deposited " << amount << " into your account." << std::endl;
}
catch(std::invalid_argument){
std::cout << "Invalid input." << std::endl;
}
【问题讨论】:
-
永远不要使用 float 或 double 来赚钱。使用整数美分。输入一个字符串,自己解析。
-
@Jeffrey 抱歉,你能解释一下你所说的 intergel 美分数是什么意思吗?
-
不使用美元计算,而是使用美分。请注意,一美元有 100 美分。根据您使用的任何货币进行调整。
-
long cents。2502.50 美元等等。这样您就不会出现舍入错误。 -
如果你使用
double,当你发现.01 + .02 不是.03 时你会非常难过,因为floating point math is broken。
标签: c++ oop error-handling try-catch