我正在编写一个类似轮盘赌的 C++ 命令行程序。用户可以输入十进制值/数字进行投注。我正在使用双类型变量来实现这一点。但是,如果我以 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;
}