我正在编写一个类似于轮盘赌的C ++命令行程序。用户可以输入十进制值/数字进行投注,我使用double类型变量使此成为可能。但是,如果例如我从1美元开始,然后输掉0.23美元,然后下注0.55美元并输掉,然后下注0.07美元并再次输掉,我就不能下注0.15美元,即使该程序声称我实际上有0.15美元(您不能下注比您拥有的钱更多)。看起来程序在错误地减少资金。然而,我仍然可以下注0.149美元。值得注意的是,我使用stringstream将用户的投注输入转换为double类型值。有人能解释一下这里发生了什么吗?
以下是我的代码:
以下是我的代码:
#include <iostream>
#include <sstream>
using namespace std; //Std namespace.
void string_to_number(string input, double& destination);
class Roulette {
private:
int randoms;
double money, choice, bet;
string input;
public:
int play = 0;
void start_amount() {
cout<<"How much money do you have?: ";
getline(cin, input);
string_to_number(input, money);
}
void betting() {
cout<<"How much money would you like to bet?: ";
getline(cin, input);
string_to_number(input, bet);
while (bet > money) {
cout<<"You can't bet more money than you have ("<<money<<" dollars). Please enter again: ";
getline(cin, input);
string_to_number(input, bet);
}
}
void choose_number() {
cout<<"Which number do you choose? (0-35): ";
getline(cin, input);
string_to_number(input, choice);
}
void random_number() {
cout<<"The wheel is spinning..."<<endl<<flush;
randoms = (rand())%36;
}
void scenarios() {
cout<<"The wheel shows number "<<randoms;
if (randoms == choice) {
money += bet;
cout<<", which means that you win "<<bet<<" dollars! You currently have "<<money<<" dollars."<<flush<<endl;
}
else {
money -= bet;
cout<<", which means that you lose "<<bet<<" dollars. You currently have "<<money<<" dollars."<<flush<<endl;
}
}
};
int main(int argc, const char * argv[])
{
srand(unsigned(time(0)));
Roulette a;
a.start_amount();
while (a.play == 0) {
a.betting();
a.choose_number();
a.random_number();
a.scenarios();
}
return 0;
}
void string_to_number(string input, double& destination) {
stringstream convert(input);
if ( !(convert >> destination) )
destination = 0;
}
<random>
头文件和std::stoi
函数。 - chrisrandoms == choice
。它们并不完全符合您的期望,因为并非所有数字都可以用双精度数表示。 - andre0.1
无法在二进制中精确表示。最简单的解决方法是不要使用小数美元,而是使用整数美分。 - user180247int
)。 - BoBTFishdouble
代表一个精确的值,总是如此。如果你使用实数算术,它可能不是你预期的值,但是doubles
并不是实数。另一方面,如果你知道自己在做什么,完全可以使用doubles
进行某些形式的精确算术运算。 - James Kanze